首页 > 解决方案 > 自定义窗口过程在一个单独的文件中

问题描述

我目前正在学习winapi,并想就如何使用不同的窗口过程设置自定义控件获得一些建议。

假设我有 20 个按钮。当鼠标悬停在每个按钮上时,我希望每个按钮做出不同的响应。比如说,“退出”按钮在悬停时绘制一个红色矩形,或者在悬停其他按钮时绘制蓝色矩形。

因此,我设置了一个自定义控制过程来处理鼠标点击、鼠标悬停等,并存储在custom.cpp. 在main.cpp中,有一个MainProc()“链接/分配”hwndButtonButtonProc()使用

CustomProcHandler = (WNDPROC)SetWindowLong(hwndButton, GWL_WNDPROC, (long)CustomProc)

主.h:

#include <windows.h>
#include <iostream>
using namespace std;

const char g_szClassName[] = "Applicaton";
static HWND hwnd, hwndButton;
static HINSTANCE hInst;
static WNDPROC buttonProcHandler;


LRESULT CALLBACK MainProc(HWND, UINT, WPARAM, LPARAM);
LRESULT CALLBACK ButtonProc(HWND, UINT, WPARAM, LPARAM);

主.cpp:

#include "main.h"

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR nCmdLine, int nCmdShow){
    WNDCLASSEX wc;
    MSG msg;

    hInst = hInstance;

    wc.cbSize = sizeof(WNDCLASSEX);
    wc.style = 0;
    wc.lpfnWndProc = WndProc;
    wc.cbClsExtra = 0;
    wc.cbWndExtra = 0;
    wc.hInstance = hInst;
    wc.hIcon = LoadIcon(hInst, 0);
    wc.hCursor = LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground = CreateSolidBrush(RGB(20, 20, 20));
    wc.lpszMenuName = 0;
    wc.lpszClassName = g_szClassName;
    wc.hIconSm = LoadIcon(hInst, 0);
    RegisterClassEx(&wc);

    hwnd = CreateWindowEx(
        WS_EX_CLIENTEDGE,
        g_szClassName,
        "The title of my window",
        WS_OVERLAPPEDWINDOW,
        CW_USEDEFAULT, CW_USEDEFAULT, 600, 400,
        NULL, NULL, hInst, NULL);

    ShowWindow(hwnd, 1);
    UpdateWindow(hwnd);

    while (GetMessage(&msg, NULL, 0, 0)) {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    return msg.wParam;
}

LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam){
    switch(msg){
        case WM_CREATE:
            button = CreateWindow("button", 0, WS_CHILD | WS_VISIBLE | BS_OWNERDRAW, 10, 10, 32, 32, hwnd, 0, hInst, 0);
            buttonProcHandler = (WNDPROC)SetWindowLong(hwndButton, GWL_WNDPROC, (long)ButtonProc);
            break;
        case WM_MOUSEMOVE:
            break;
        case WM_CLOSE:
            DestroyWindow(hwnd);
            break;
        case WM_DESTROY:
            PostQuitMessage(0);
            break;
        default: 
            return DefWindowProc(hwnd, msg, wParam, lParam);
    }
    return 0;
}

自定义.cpp:

#include "main.h"

LRESULT CALLBACK ButtonProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam){
    switch(msg){
        case WM_CREATE:
            break;
        case WM_MOUSEMOVE:
            break;
        case WM_LBUTTONDOWN:
            break;
        default:
            return CallWindowProc(buttonProcHandler, hwnd, msg, wParam, lParam);
    }
    return 0;
}

问题是按钮消失了......但是当我进入buttonProc()里面时,main.cpp一切正常。

所以,我猜我在声明像static WNDPROC buttonProcHandler.

我知道我在做的是完全错误的,并且有更好的方法来做。我只是不知道那是什么。

任何人都可以帮助/教我创建自定义程序的标准方法吗?

标签: c++winapiglobal-variablessubclassing

解决方案


推荐阅读