gpt4 book ai didi

c# - 短按和长按处理

转载 作者:行者123 更新时间:2023-11-28 02:37:37 25 4
gpt4 key购买 nike

如果我短按键盘或长时间按键盘,我想执行 2 个不同的命令。如果我按住某个键,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)可以解决我的问题。

最佳答案

您可以尝试以下操作。此示例仅挂接到窗体的 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);
}
}

关于c# - 短按和长按处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26977904/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com