自定义窗口proc在单独的文件中

时间:2018-05-16 17:44:04

标签: c++ winapi global-variables subclassing

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

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

因此,我设置了一个自定义控制程序来处理鼠标点击,鼠标悬停等,并存储在custom.cpp中。在main.cpp中,有一个MainProc()使用

“链接/分配”hwndButtonButtonProc()
CustomProcHandler = (WNDPROC)SetWindowLong(hwndButton, GWL_WNDPROC, (long)CustomProc)

main.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);

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

custom.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这样的全局变量时我做错了。

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

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

0 个答案:

没有答案