C++ Window Button

Started by
5 comments, last by bprogrammer 18 years, 9 months ago
How would you put a button into a C++ window and make it do an action? (I.E. display a message box.) And it's not like I haven't Googled it myself - all the examples are for .NET, which I have NO interest in. [Edited by - orcfan32 on July 18, 2005 10:22:30 PM]
The best thing to do is just choose whatever you think you'd prefer, and go for it. -Promit
Advertisement
MessageBox (NULL, "Message goes here", "Title goes here", MB_OK);

Look up MessageBox() in MSDN if you want more information.
You should specify which compiler you are using, which API and whether you are using a dialog/resource editor to create the window or are creating it all in code.

Using MFC and the MSVC dialog editor, it's simply a case of placing a button control on the form and double-clicking on it will create a method that will be executed when the button is clicked at runtime.

Using plain Win32 without the dialog editor, you'd call CreateWindow/CreateWindowEx, specifying "BUTTON" as the window class and your main window's HWND as parent. When clicked, the button sends a WM_COMMAND message to its owner. Win32 tutorial.
Kippesoep
If you are using MFC but you are not using the Forms designer, you would probably use the CButton class. However, Kippesoep is right - you need to give us a little more information about the language/os/setup you are using.
"Absorb what is useful, reject what is useless, and add what is specifically your own." - Lee Jun Fan
switch(HIWORD(wParam)) {
case BN_CLICKED:
if(LOWORD(wParam)== BUTTON_ID){
//do what ever here
break;
}

just like that

I hade the same question and some one in these forums showed me
Language = C++
Compiler = Dev-C++
OS = Windows XP
The best thing to do is just choose whatever you think you'd prefer, and go for it. -Promit
Assuming it is not MFC, you could do the following:

switch( message )
{
case WM_CREATE:
hButton = CreateWindow( "Button", "Click Me", BS_PUSHBUTTON | WS_VISIBLE | WS_CHILD | WS_TABSTOP, 10, 10, 75, 20, hWnd, (HMENU)ID_BUTTON1, NULL, NULL );
break;

case WM_COMMAND:
switch( wParam )
{
case ID_BUTTON1:
MessageBox( NULL, "You have clicked me!", "Alert", MB_OK );
break;
}
}

Where hButton is declared as HWND and ID_BUTTON1 is defined as a global.

This topic is closed to new replies.

Advertisement