【问题标题】:How to programmatically press combination of keys at once in a UWP app如何以编程方式在 UWP 应用程序中一次按下组合键
【发布时间】:2021-04-26 09:56:59
【问题描述】:

我想在C#中同时按下Ctrl+w

[DllImport("user32.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern void keybd_event(uint bVk, uint bScan, uint dwFlags, uint dwExtraInfo);

public static void pressKey(KeyCode keycode)
{
    keybd_event(Convert.ToUInt16(keycode), 0, 0, 0);
}

此方法一次只能按一个键。

编辑:这不是 Windows 窗体应用程序,这是 UWP 应用程序。

这是一个 UWP 应用程序,因此 windows 窗体方法很可能在这里不起作用,请停止将我的问题标记为类似问题。

【问题讨论】:

  • 不,这是一个 UWP 应用程序,所以我认为发送密钥方法在这里不起作用,因为该方法使用 Windows 窗体。
  • 如果答案已经解决了您的问题,请mark它被接受

标签: c# uwp uwp-xaml keyboard-events keycode


【解决方案1】:

如何在 UWP 应用中以编程方式一次按下组合键

您可以参考Keyboard accelerators文档制作键盘加速器,在xaml中定义UWP控件的键盘加速器

<Button Content="Save" Click="OnSave">
  <Button.KeyboardAccelerators>
    <KeyboardAccelerator Key="S" Modifiers="Control" />
  </Button.KeyboardAccelerators>
</Button>

在后面的代码中定义

private void TextBlock_PreviewKeyDown(object sender, KeyRoutedEventArgs e)
 {
    var ctrlState = CoreWindow.GetForCurrentThread().GetKeyState(Windows.System.VirtualKey.Control);
    var isCtrlDown = ctrlState == CoreVirtualKeyStates.Down || ctrlState 
        ==  (CoreVirtualKeyStates.Down | CoreVirtualKeyStates.Locked);
    if (isCtrlDown && e.Key == Windows.System.VirtualKey.S)
    {
        // Your custom keyboard accelerator behavior.
        
        e.Handled = true;
    }
 }

【讨论】:

    猜你喜欢
    • 2018-08-12
    • 2019-03-10
    • 1970-01-01
    • 2019-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多