我想做两个不同的命令,如果我按下键盘短时间或长时间。如果我持有密钥,Windows将向我发送多个keyDown和KeyUp事件。
现在就来。我这么做是为了应付“长新闻”
c++:
if (pMsg->message == WM_KEYDOWN)
{
return keyboardManager->Execute( (KeyboardCommand)pMsg->wParam, BOOL (HIWORD(pMsg->lParam) & KF_REPEAT) == 0 ) )
}注意: pMsg是MSG (winuser.h),KeyboardCommand是一个带有虚拟密钥代码值的枚举
c#:
public Boolean Execute( KeyboardCommand _command, Boolean _first )
{
switch(_command)
{
case (KeyboardCommand.myCommand):
TimeSpan timeLapse = DateTime.Now - m_TimeKeyDown;
if (_first)
{
m_TimeKeyDown = DateTime.Now;
m_LongCommandExecuted = false;
}
else if (!m_LongCommandExecuted && timeLapse.TotalMilliseconds > 500)
{
m_LongCommandExecuted = true;
handled = ExecuteAction();
}
break;
case (KeyboardCommand.otherCommand):
break;
}
return handled;
}你对如何处理“短新闻”有什么想法吗?知道KeyUp是否是最后一个keyUp (真正的keyUp)可以解决我的问题。
发布于 2014-11-17 21:29:33
我找到了答案。
c++:
if (pMsg->message == WM_KEYUP || pMsg->message == WM_KEYDOWN)
{
return keyboardManager->Execute( (KeyboardCommand)pMsg->wParam, BOOL (HIWORD(pMsg->lParam) & KF_REPEAT) == 0, (HIWORD(pMsg->lParam) & KF_UP) == KF_UP, pMsg->message == WM_KEYDOWN )
}c#:
public Boolean Execute( KeyboardCommand _command, Boolean _first, Boolean _last, Boolean _keyDown )
{
if (_keyDown)
{
switch (_command)
{
case (KeyboardCommand.otherCommand):
handled = ExecuteCommand();
break;
}
}
switch (_command)//Short press and long press events
{
case (KeyboardCommand.mycommand):
if (_first)
{
m_TimeKeyDown = DateTime.Now;
m_LongCommandExecuted = false;
}
else
{
TimeSpan timeLapse = DateTime.Now - m_TimeKeyDown;
if (!m_LongCommandExecuted && timeLapse.TotalMilliseconds > 500)//long press
{
m_LongCommandExecuted = true;
handled = myLongcommand();
}
if (!m_LongCommandExecuted && _last)//short press
{
m_LongCommandExecuted = true;
handled = myShortcommand();
}
}
break;
}
//some other jazz
}发布于 2014-11-17 19:38:34
你可以尝试下面这样的方法。这个例子只会链接到表单的KeyDown和KeyUp事件,因此您需要修改它以满足您的需要。
//consider keys held less than one second a short keypress event
const double longThresholdMs = 1000.0;
Dictionary<Keys, DateTime> keyDownTimes = new Dictionary<Keys, DateTime>();
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (!keyDownTimes.ContainsKey(e.KeyCode))
{
keyDownTimes[e.KeyCode] = DateTime.Now;
}
}
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
if (keyDownTimes.ContainsKey(e.KeyCode))
{
if (DateTime.Now.Subtract(keyDownTimes[e.KeyCode]).TotalMilliseconds > longThresholdMs)
{
Console.Out.WriteLine(e.KeyCode + " long press");
}
else
{
Console.Out.WriteLine(e.KeyCode + " short press");
}
keyDownTimes.Remove(e.KeyCode);
}
}https://stackoverflow.com/questions/26977904
复制相似问题