问题描述
我想在 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);
}
编辑:这不是 Windows 窗体应用程序,这是 UWP 应用程序。
这是一个 UWP 应用程序,因此 windows 窗体方法很可能在此处不起作用,请停止将我的问题标记为类似问题。
解决方法
如何在 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;
}
}