开发者

Windows API - Beginner help

I try to create a very simple app using windows API.

I've done some small apps in console. This is the first time I do with Win32 apps. I've searched and found a document from forgers which is recommended in this site. But I try to write very first line:

 #include <stdafx.h>
 #include <windows.h>

 int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevI开发者_如何学JAVAnstance,
     LPSTR lpCmdLine, int nCmdShow)
 {
     MessageBoxW(NULL, "Good bye Cruel World", "Note", MB_OK);
     return 0;
 }

But it doesn't work (erased lines from default project created by VS 2008 and write these lines).


There are two versions of most windows API calls, one which takes single byte string and one which takes 2 byte unicode strings. The single byte one has an A on the end of the name and the 2 byte one has a W. There are macros defined in windows.h so that if you leave the letter out it picks one or the other depending on compiler macros.

In your code you write -

MessageBoxW (NULL, "Good bye Cruel World", "Note", MB_OK ); 

You are calling the wide character version of the API with single byte strings which won't work. Either change to MessageBoxA or change your strings to wide strings -

MessageBoxW (NULL, L"Good bye Cruel World", L"Note", MB_OK ); 


Remove the first line. What remains is a valid Windows program, which should compile under any IDE. Your problem is the stdafx.h header which is an artefact of VS, and you may have other problems if you try to "reuse" an existing VS project. If you want to nkow how compilation really works, it's a good idea to build some simple apps not using an IDE, but a command line compiler like MinGW.

And in future, post what error messages you are getting using copy and paste.


You need at least a message loop to run, in order for the application to process messages:

while(GetMessage(&msg, NULL, 0, 0))
{
    TranslateMessage(&msg);
    DispatchMessage(&msg);
}

There are many tutorials on the message loop on the web, such as here:

  • http://www.winprog.org/tutorial/message_loop.html

If you're just starting GUI programming, you're best off reading a book, and working through the examples. Petzold is a classic. Learning programming by collecting snippets of partially working code cribbed from random web pages is going to be time-consuming, difficult and patchy. A well-written book will lead you through the fundamentals and explain things in stages. Have fun!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜