用 C++ 创建一个按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26478979/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 11:37:04  来源:igfitidea点击:

Creating a Button With C++

c++windowswinapibutton

提问by wuqiang

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.

我正在用 C++ 设计一个游戏,目前正在我的主菜单上工作,其中包括三个难度级别的三个按钮。问题是,我实际上不知道如何在 C++ 中创建按钮。我遇到了一些关于如何执行此操作的 YouTube 教程,但是制作视频的两个人只是将这段代码插入到现有程序中,我无法弄清楚如何让它与我的代码一起工作。

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.

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

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:

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

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.

有任何想法吗?我真的很陌生,所以任何帮助或建议将不胜感激。

回答by wuqiang

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;
}