Saturday, August 2, 2008

Hello World - c++ Windows Application

In this post I'm going to explain the details of writing a hello world program for windows. To start we should look at the version for a console application:


#include <iostream&rt;
using namespace std;
void main() {
cout << "Hello World" << endl;
}


For windows it isn't much different. But instead of declaring a main we need to instead declare a WinMain.


#include <windows.h&rt;

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShowCmd) {
MessageBox(NULL,L"Hello World",L"MyCaption",MB_ICONINFORMATION | MB_OK);
}


1. We include windows.h to give us access to the windows library functions.

2. The keyword WINAPI instructs the program to reverse the argument list. For our purposes this doesn't matter but under the hood windows needs this.

3. HINSTANCE is a handle to an instance. The main program receives a instance to itself (hinstance) and a handle to a previous instance of the same program. The previous instance is legacy and is NULL for modern applications. But is still provided for legacy code.

4. lpCmdLine is the entire command string that was used to execute the program.

5. nCmdShowCmd are options indicating how the window should open.

6. Once our method is called we can then call MessageBox to display the message.

We can now look into the MessaegBox command in more detail. The signature for the command is:


int MessageBox(HWND hWnd,
LPCTSTR lptext,
LPCTSTR lpcaption,
UINT utype);


The first argument HWND, is a handle to the window the created this message box. In our case we haven't created a window, so we supply NULL which instructs Windows to have the message box originate from the desktop.

lpText is a pointer to the text to display

lpcaption is a pointer to the caption of the message box.

uType is a parameter that specifies what type of message box, exclamation, information, etc. These are set by 'ORing' constant flags together.

No comments: