用C++创建一个按钮

Bet*_*ner 2 c++ windows winapi button

我正在设计一个用C++编写的游戏,目前正在我的主菜单上工作,其中包括三个难度级别的三个按钮.问题是,我实际上并不知道如何在C++中创建一个按钮.我遇到了几个关于如何做到这一点的YouTube教程,但是两个人都在做视频,只是将这段代码插入到现有程序中,而我却无法弄清楚如何使用我的代码.

这是我到目前为止:

#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;
} 
Run Code Online (Sandbox Code Playgroud)

当我运行它时,控制台弹出正确的背景颜色和消息,但没有按钮.谁能告诉我我做错了什么?我确定它与所有这些NULL有关,但不确定要用什么替换它们.

这就是YouTube视频中的代码,但就像我说的那样,它正处于已经创建的程序中间:

CreateWindow(TEXT("button"), TEXT("Hello"), 
   WS_VISIBLE | WS_CHILD,
   10, 10, 80, 25,
   hwnd, (HMENU) 1, NULL, NULL);
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?我真的很陌生,所以任何帮助或建议都会非常感激.

wuq*_*ang 6

您应该创建一个消息循环并在循环之前显示该按钮.

#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;
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢一堆!必须调整定位,但这有效:-) (2认同)