Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

windows

winapi

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 button using ONLY Windows API and C. No C++ please.

Thanks for your time! :)

like image 341
Ishan Sharma Avatar asked Nov 20 '25 22:11

Ishan Sharma


1 Answers

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.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!