c++ - 在类中包装 WinApi 按钮功能
问题描述
我正在尝试在 C++ 中创建一个按钮类来包装WinApi
. 它是多态的,其子对象是按钮或单选按钮之类的对象。
我遇到的问题是我不知道如何在BN_CLICKED
发生事件时存储按钮处理程序。我应该将它存储在类中还是每次Draw()
调用时都会重置它。这是我的按钮和按钮代码,谢谢:
#pragma once
#include "pch.h"
namespace CH
{
class Button
{
protected:
int x, y, w, h;
std::string text;
virtual bool Draw(HWND hWnd) = 0;
virtual bool Draw(HWND hWnd, long styles) = 0;
public:
Button(int xPos, int yPos, int width, int height, std::string content)
{
x = xPos;
y = yPos;
w = width;
h = height;
text = content;
}
~Button() = default;
inline int getX() { return x; }
inline int gety() { return y; }
inline int getW() { return w; }
inline int getH() { return h; }
};
}
////////
// PushButton.h
////////
#pragma once
#include "Button.h"
namespace CH
{
class PushButton
: public Button
{
public:
PushButton(HWND& hWnd, int xPos, int yPos, int width, int height, std::string content)
: Button(xPos,yPos,width,height,content)
{
std::wstring stemp = std::wstring(text.begin(), text.end());
handler = CreateWindow(
L"BUTTON", // Predefined class; Unicode assumed
stemp.c_str(), // Button text
WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON, // Styles
x, // x position
y, // y position
w, // Button width
h, // Button height
hWnd, // Parent window
NULL, // No menu.
(HINSTANCE)GetWindowLongPtr(hWnd, GWLP_HINSTANCE),
NULL); // Pointer not needed.
}
};
}
解决方案
按钮HWND
句柄由创建CreateWindow()
并在窗口关闭或销毁之前一直有效。
它不会被重置Draw()
,您可以简单地将其作为成员存储在基类 ( Button
) 中。确保使用构造函数对其进行初始化,nullptr
以便在创建按钮之前它是无效的。
请注意,WinAPI 按钮已经有自己的内部Draw()
功能。如果你想实现自己的,它会很快变得非常复杂。您可以在没有它的情况下开始,以保持简单。
推荐阅读
- spring - 如何使用 Spring Boot 和 JPA 在 GET 请求中获取所有一对多实体
- python - Django 是否为模板使用内置变量名?
- ruby-on-rails - 模型中表的未知主键 (ActiveRecord)
- java - 如果没有依赖注入,Java Spring 中的 XML IoC 有什么意义?
- functional-programming - 如何从方案中的函数返回值
- javascript - 对象作为 React 子级无效。如果您打算渲染一组子项,请改用数组 - 错误 Solidity - React
- php - 如何使用 PHP 解析网页内的图像?
- reactjs - Gatsby 中的 Prismic 插件出现“无效插件选项”错误
- laravel - 如何根据登录用户隐藏按钮?在HTML
- xpath - 为什么带有 XPATH 的 IMPORTXML 除了返回预期结果之外还返回意外的空白行?