【发布时间】:2012-04-12 15:43:06
【问题描述】:
如何通过按Ctrl+A来选择编辑控件中的所有文本? 我可以在 WndProc 中为父窗口捕获 Ctrl+A。 但我不知道如何捕捉应用于编辑控制的 ctrl+a 。 我也尝试使用加速器,但它再次仅适用于父窗口。 谢谢。 编辑:第一最简单的方法 此方法基于@phord 在此问题中的回答: win32 select all on edit ctrl (textbox)
while( (bRet = GetMessage( &msg, NULL, 0, 0 )) != 0)
{
if (bRet == -1)
{
// handle the error and possibly exit
}
else
{
if (msg.message == WM_KEYDOWN && msg.wParam == 'A' && GetKeyState(VK_CONTROL) < 0)
{
HWND hFocused = GetFocus();
wchar_t className[6];
GetClassName(hFocused, className, 6);
if (hFocused && !wcsicmp(className, L"edit"))
SendMessage(hFocused, EM_SETSEL, 0, -1);
}
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
编辑:第二种方法 需要使用 CreateAcceleratorTable + TranslateAccelerator 函数:
//全局变量:
enum {ID_CTRL_A = 1};
HACCEL accel;
//主程序
ACCEL ctrl_a;
ctrl_a.cmd = ID_CTRL_A; // Hotkey ID
ctrl_a.fVirt = FCONTROL | FVIRTKEY;
ctrl_a.key = 0x41; //'A' key
accel = CreateAcceleratorTable(&ctrl_a, 1); //we have only one hotkey
//GetMessage 循环的样子
while( (bRet = GetMessage( &msg, NULL, 0, 0 )) != 0)
{
if (bRet == -1)
{
// handle the error and possibly exit
}
else
{
if (!TranslateAccelerator(hWnd, accel, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
}
//在 WndProc 中我们必须添加下一个案例
case WM_COMMAND:
{
if (LOWORD(wParam) == ID_CTRL_A && HIWORD(wParam) == 1)
{
//on which control there was pressed Ctrl+A
//there is no way of getting HWND through wParam and lParam
//so we get HWND which currently has focus.
HWND hFocused = GetFocus();
wchar_t className[6];
GetClassName(hFocused, className, 6);
if (hFocudsed && !wcsicmp(className, L"edit"))
SendMessage(hFocused, EM_SETSEL, 0, -1);
}
}
break;
case WM_DESTROY:
{
DestroyAcceleratorTable(accel);
PostQuitMessage(0);
}
break;
如您所见,这非常简单。
【问题讨论】:
-
我以为
EDIT控件会自动处理此问题 -
@DavidHeffernan 一些文件说如果 ES_MULTILINE ctrl+a 不起作用。但是我没有那个风格还是有问题。
-
你看这个问题了吗? stackoverflow.com/questions/291792/…
-
@MikeKwan 是的。我认为在所有答案中,这个问题没有正确的答案。正确答案在这里。
-
@UnhandledException:这个答案实际上包含了您所写的内容。 stackoverflow.com/a/315720/712358
标签: winapi visual-c++