C++Builder 程序员博客
27 Nov
一个简单的SDK程序, CreateWindow了一个Button子窗口,接着用SetWindowLong函数来指定该Button的回调函数为ButtonProc。程序的目标效果为点击窗口中的按钮后,会在窗口中输出一段文字。
问题在于用SetWindowLong函数为Button指定的回调函数未起作用,所以也就无法得到目标效果了。
下面是完整的程序代码,不知问题出在哪儿了
#include <windows.h> #define IDC_BUTTON 101 BOOL InitApplication(HINSTANCE); BOOL InitInstance(HINSTANCE, int); LRESULT CALLBACK WndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); LRESULT CALLBACK ButtonProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); //int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int); static TCHAR szAppName[] = TEXT("MainWClass"); WNDPROC BTNProc; HWND hwndButton; int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { MSG msg; if (!InitApplication(hInstance)) { return (FALSE); } if (!InitInstance(hInstance, nCmdShow)) { return (FALSE); } while(GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return (msg.wParam); } BOOL InitApplication(HINSTANCE hinstance) { WNDCLASS wcx; //wcx.cbSize = sizeof(wcx); wcx.style = CS_HREDRAW | CS_VREDRAW; wcx.lpfnWndProc = (WNDPROC)WndProc; wcx.cbClsExtra = 0; wcx.cbWndExtra = 0; wcx.hInstance = hinstance; wcx.hIcon = LoadIcon(NULL, IDI_APPLICATION); wcx.hCursor = LoadCursor(NULL, IDC_ARROW); wcx.hbrBackground = GetStockObject(WHITE_BRUSH); wcx.lpszMenuName = NULL; wcx.lpszClassName = szAppName; return (RegisterClass(&wcx)); } BOOL InitInstance(HINSTANCE hinstance, int nCmdShow) { HWND hwnd; HINSTANCE hinst = hinstance; hwnd = CreateWindow(szAppName, TEXT("SDK"), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hinstance, NULL); if (!hwnd) { return (FALSE); } ShowWindow(hwnd, nCmdShow); UpdateWindow(hwnd); return (TRUE); } LRESULT CALLBACK WndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { HDC hdc; RECT rect; PAINTSTRUCT ps; //RECT rect; switch(uMsg) { case WM_CREATE: hwndButton = CreateWindow(TEXT("BUTTON"), TEXT("OK"), WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON, 10, 10, 100, 27, hwnd, (HMENU) IDC_BUTTON, (HINSTANCE) GetWindowLong(hwnd, GWL_HINSTANCE), NULL); BTNProc = (WNDPROC) SetWindowLong(hwndButton, GWL_WNDPROC, (LPARAM)(WNDPROC)ButtonProc); return 0; case WM_PAINT: hdc = BeginPaint(hwnd, &ps); EndPaint(hwnd, &ps); break; case WM_DESTROY: PostQuitMessage(0); } return DefWindowProc(hwnd, uMsg, wParam, lParam); } LRESULT CALLBACK ButtonProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { HDC hdc; RECT rect; switch(uMsg) { case WM_PAINT: break; case WM_COMMAND: switch(LOWORD(wParam)) { case IDC_BUTTON: hdc = GetDC(hwnd); TextOut(hdc, 100, 100, TEXT("Mouse Left Button Click!"), strlen("Mouse Left Button Click!")); ReleaseDC(hwnd, hdc); ValidateRect(hwnd, &rect); break; } break; } return CallWindowProc(BTNProc, hwnd, uMsg, wParam, lParam); }
关注
你的回调函数已经起作用了,问题是Button本身是接收不到WM_COMMAND消息的,这个消息是用来通知父窗体的,只要把WM_COMMAND放到WndProc里就能收到。
楼上正解.当Button被点击,会发送BN_CLICKED给你窗口,所以WM_COMMAND只能写在父窗口中