首页 > 解决方案 > 在类中包装 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.
    }

};


}

标签: c++winapi

解决方案


按钮HWND句柄由创建CreateWindow()并在窗口关闭或销毁之前一直有效。

它不会被重置Draw(),您可以简单地将其作为成员存储在基类 ( Button) 中。确保使用构造函数对其进行初始化,nullptr以便在创建按钮之前它是无效的。

请注意,WinAPI 按钮已经有自己的内部Draw()功能。如果你想实现自己的,它会很快变得非常复杂。您可以在没有它的情况下开始,以保​​持简单。


推荐阅读