我在WM_CREATE
回调的WindowProc
消息中创建了一个自定义子类按钮。这是创建和子类说明,以及用于控制按钮状态的结构:
static button_state btnstateBtnInstall;
hBtnInstall = CreateWindow(WC_BUTTON, L"Button", WS_CHILD | WS_VISIBLE, (window_width / 2) - (btn_install_width / 2), window_height - (window_height / 6) - (btn_install_height / 2), btn_install_width, btn_install_height, hwnd, (HMENU)HMENU_btn_install, NULL, NULL);
SetWindowSubclass(hBtnInstall, BtnInstallProc, 0, (DWORD_PTR)&btnstateBtnInstall);
结构定义如下:
struct button_state
{
bool pushed;
button_state() { pushed = false; }
};
子类过程的编码如下:
LRESULT CALLBACK BtnInstallProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam, UINT_PTR uIdSubClass, DWORD_PTR dwRefData)
{
button_state* state = (button_state*)dwRefData;
// Omitted part where I create brushes and font to be used for painting
switch (msg)
{
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
RECT rc = ps.rcPaint;
POINT pt;
GetCursorPos(&pt);
ScreenToClient(hwnd, &pt);
BOOL hover = PtInRect(&rc, pt);
if (state->pushed)
{
// Pushed
FillRect(hdc, &rc, hBrPushed);
}
else if (hover)
{
// Mouse over
FillRect(hdc, &rc, hBrHover);
}
else
{
// Normal
FillRect(hdc, &rc, hBrNormal);
}
SetBkMode(hdc, TRANSPARENT);
SetTextColor(hdc, RGB(255, 255, 255));
SelectFont(hdc, SegoeUI);
static LPCWSTR InstallBtnTxt = L"Install";
static int InstallBtnTxtLen = static_cast<int>(wcslen(InstallBtnTxt)); // Should be a safe cast, for small arrays like this one
DrawText(hdc, InstallBtnTxt, InstallBtnTxtLen, &rc, DT_SINGLELINE | DT_CENTER | DT_VCENTER);
EndPaint(hwnd, &ps);
return 0;
}
case WM_LBUTTONDOWN:
{
state->pushed = true;
break;
}
case WM_LBUTTONUP:
{
state->pushed = false;
break;
}
// Omitted part where I handle WM_DESTROY to do cleanup
}
return DefSubclassProc(hwnd, msg, wParam, lParam);
}
为了将我的按钮的行为与标准按钮的行为进行比较,我创建了另一个没有子类并且仅使用标准BUTTON
类和WS_VISIBLE | WS_CHILD
属性的按钮。
从随附的gif文件中可以看到,当我反复单击标准班级按钮时,每次单击都会产生动画,而当我多次点击我创建的按钮时使用此代码,似乎并没有捕获到每次点击,但(如您所见)却捕获了其中的50%。
我想念什么?为什么我的按钮不能像标准类中的按钮那样反应灵敏?
TL; DR :在我的子类按钮上缓慢单击时,绘画是正确的。从我的图像中可以看到,重复单击时,我的按钮和标准按钮之间的差异很大。如何使我的控件像标准控件一样灵敏?
答案 0 :(得分:4)
快速单击时,某些WM_LBUTTONDOWN
消息将被WM_LBUTTONDBLCLK
替代(默认双击处理)。您需要像处理WM_LBUTTONDOWN
消息一样处理它。
case WM_LBUTTONDOWN:
case WM_LBUTTONDBLCLK: // <-- Added
{
state->pushed = true;
break;
}