开发者

Programming in C With Windows API: How To Draw A Command Button

Well, I am building a college project in C. GUI has not been taught yet but I want my program to be better, so I am learning Windows API.

I am following this tutorial here: http://www.winprog.org/tutorial/start.html and it is quite good. It explains lot of things but I am not able to find one thing(even searched Google but everything is oriented towards C++ or C#):

How do I draw a command button inside the drawn window(which I have learned) and how to accept events for it?

Can you please answer or point me to a good page that explains how I can create a command b开发者_StackOverflow社区utton using ONLY Windows API and C. No C++ please.

Thanks for your time! :)


This is a tutorial I highly recommend on the Win32 API user interface functions. It's excellent. Roughly speaking, in your callback function (LRESULT CALLBACK WndProc( HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam ) you have several options you can catch:

switch(msg)  
{
    case WM_CREATE:
        break;

    case WM_COMMAND:
        break;
    /* .. */
}

What you need to do on WM_CREATE is something like this:

HWND hWnd_button = CreateWindow(TEXT("button"), TEXT("Quit"),    
                 WS_VISIBLE | WS_CHILD ,
                 20, 50, 80, 25,        
                 hwnd, (HMENU) 1, NULL, NULL);  

The reason I've stored the HWND of that button is that if you want to alter the button at a later date, you'll need that Handle as an argument for SendMessage(). Now, next up, catching a click. When the button is clicked, it sends WM_COMMAND to the parent window with the HMENU casted argument (1 in this case) in wParam. This works for every control you create (menus, checkboxes etc - if they post more complicated options they may be present in lParam). So:

case WM_COMMAND:
    if (LOWORD(wParam) == 1) {
        DestroyWindow();
        /* or SendMessage(hwnd, WM_CLOSE,0,0); see commments */
    }
    break;

Catches that particular option. Inside the if handles that button event.


Simply use CreateWindow with class name "BUTTON", style BS_PUSHBUTTON and parent window as your existing drawn window. The x and y coordinates select the top-left button position in the window. The window name is the text on the button. Also, remember to call ShowWindow on the returned handle.

edit: To accept events for it, first define an ID value like:

#define ID_MYBUTTON 1

Then pass that into the menu-parameter of the CreateWindow call. In your main windows message proc you can now find message by testing for:

if(message == WM_COMMAND && HIWORD(wParam) == BN_CLICKED && LOWORD(wParam) == ID_MYBUTTON) { /* button was clicked */ }

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜