Reputation:
I'm working on designing a game in C++ and am currently working on my main menu which includes three buttons for three difficulty levels. The problem is, I don't actually know how to create a button in C++. I came across a couple of YouTube tutorials on how to do this, but both guys doing the videos were just inserting this piece of code into an existing program and I'm having trouble figuring out how to get it to work with my code.
Here is what I have so far:
#include "stdafx.h"
#include <iostream>
#include <Windows.h>
using namespace std;
int main()
{
system("color e0");
cout << "Can You Catch Sonic?" << endl;
cout << "Can you find which block Sonic is hiding under? Keep your eyes peeled for that speedy hedgehog and try to find him after the blocks stop moving" << endl;
CreateWindow(TEXT("button"), TEXT("Easy"), WS_VISIBLE | WS_CHILD,
10, 10, 80, 25, NULL, NULL, NULL, NULL);
return 0;
}
When I run this, the console pops up with the correct background color and messages, but there is no button. Can anyone tell me what I'm doing wrong? I'm sure it has something to do with all those NULLs, but not sure what to replace them with.
This is what the code from the YouTube video was, but like I said, it was in the middle of a program that had already been created:
CreateWindow(TEXT("button"), TEXT("Hello"),
WS_VISIBLE | WS_CHILD,
10, 10, 80, 25,
hwnd, (HMENU) 1, NULL, NULL);
Any ideas? I'm really new to this so any help or suggestions would be greatly appreciated.
Upvotes: 3
Views: 59913
Reputation: 644
You should create a message loop and show the button before the loop.
#include <Windows.h>
int _tmain(int argc, _TCHAR* argv[])
{
MSG msg;
//if you add WS_CHILD flag,CreateWindow will fail because there is no parent window.
HWND hWnd = CreateWindow(TEXT("button"), TEXT("Easy"), WS_VISIBLE | WS_POPUP,
10, 10, 80, 25, NULL, NULL, NULL, NULL);
ShowWindow(hWnd, SW_SHOW);
UpdateWindow(hWnd);
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return (int) msg.wParam;
}
Upvotes: 7