修改回调函数

今天在十五派学习的时候遇到了这样一道题:

点击一个按钮,在按钮本身的消息中弹出对话框,而不是在COMMAND消息中弹出对话框

题意可以大致理解为,点击按键后,将主窗口的回调函数修改为按键的回调函数

实例代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <windows.h>
#include <tchar.h>
#include "resource.h"

DLGPROC DlgWndProc = 0;

INT_PTR CALLBACK BtnWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
INT_PTR CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);

INT_PTR CALLBACK BtnWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_LBUTTONDOWN:
MessageBox(0, TEXT("这是按钮消息"), 0, 0);
SetWindowLong(hWnd, GWL_WNDPROC, (LONG)DlgWndProc);
break;
default:
break;
}
return DlgWndProc(hWnd, uMsg, wParam, lParam);
}

INT_PTR CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_COMMAND:
{
int nId = LOWORD(wParam);
if (nId == IDC_BUTTON1)
{
MessageBox(0, TEXT("这是对话框消息"), 0, 0);
//WM_COMMAND的lParam保存的是子窗口句柄
DlgWndProc = (DLGPROC)SetWindowLong((HWND)lParam, GWL_WNDPROC,(LONG)BtnWndProc);
}
break;
}
case WM_CLOSE:
EndDialog(hWnd, 0);
break;
default:
break;
}

//对话框的回调函数返回值为0
return 0;
}

INT WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE, LPTSTR, INT)
{
//SetwindowLong SetCLassLong
//GetWindowLong GetClassLong

//模态对话框用 DialogBox
//非模态用的是 CreateDialog
//注意::非模态 需要自己实现消息循环
DlgWndProc = WndProc;

HWND hwnd = CreateDialog(hInstance, MAKEINTRESOURCE(IDD_DIALOG1), NULL, DlgWndProc);

//注意:-------要显示并更新窗口
ShowWindow(hwnd, SW_SHOW);
UpdateWindow(hwnd);
MSG msg = { 0 };

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

return 0;
}