-1

I want to press Ctrl+w at the same time in C#.

[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);
}

This method will only press one key at a time.

Edit: This is not a windows form application, this is UWP app.

This is a UWP application so windows form methods most likely won't work here, please stop marking my question a similar question.

stuartd
  • 70,509
  • 14
  • 132
  • 163
  • No, this is a UWP app so send keys method won't work here i think, since the method uses windows forms. – Hana Munamana Apr 26 '21 at 10:03
  • Does [How to Simulate a Tab Key Press with Code in UWP](https://stackoverflow.com/questions/56636716/how-to-simulate-a-tab-key-press-with-code-in-uwp) answer your question? – stuartd Apr 26 '21 at 10:08

1 Answers1

0

How to programmatically press combination of keys at once in a UWP app

You could refer Keyboard accelerators document to make the keyboard accelerator, define the keyboard accelerator for UWP control in the xaml

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

Define in the code behind

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;
    }
 }
Nico Zhu
  • 32,367
  • 2
  • 15
  • 36