0

I want to capture a Key Press and get the e.Key Enum int value.


This captures and displays the key that was pressed.

XAML

<ToggleButton x:Name="btnDPad_L"
              Content="{Binding DPad_L_Text}" 
              HorizontalAlignment="Left" 
              VerticalAlignment="Top"
              Margin="80,172,0,0" 
              Height="30"
              Width="30" 
              PreviewKeyDown="btnDPad_L_PreviewKeyDown" />

C#

private void btnDPad_L_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
    int keyEnum = (int)e.Key; // Capture

    MessageBox.Show(e.Key.ToString());   // Letter
    MessageBox.Show(keyEnum.ToString()); // Enum
}

Problem

This gives the System.Windows.Input Micrcorosft Keys Enum int values.

System.Windows.Input.Keys Enum

W = 66  
A = 44   
S = 62  
D = 47  

I need the System.Windows.Forms KeyEventArgs different int values.

System.Windows.Forms.Keys Enum

W = 87  
A = 65  
S = 83  
D = 68  

Errors

When I try to use System.Windows.Forms.KeyEventArgs I get the errors:

No overload for 'btnDPad_L_PreviewKeyDown' matches delegate 'KeyEventHandler'

I try to attach a handler to Window_Loaded event:

btnDPad_L.KeyDown += new System.Windows.Forms.KeyEventArgs(btnDPad_L_PreviewKeyDown);

cannot convert from 'method group' to 'Keys'

BionicCode
  • 1
  • 4
  • 28
  • 44
Matt McManis
  • 4,475
  • 5
  • 38
  • 93
  • 1
    Are you in WPF or windows forms? The class for arguments to the event, `KeyEventArgs`, is not an event handler delegate type. You want [`System.Windows.[Input or Forms as appropriate].KeyEventHandler`](https://learn.microsoft.com/en-us/dotnet/api/system.windows.uielement.keydown?view=netframework-4.8) -- or better yet, just add the bare delegate: `btnDPad_L.KeyDown += btnDPad_L_PreviewKeyDown;`. That'll be fine if it's the correct prototype. – 15ee8f99-57ff-4f92-890c-b56153 Aug 06 '19 at 16:59
  • @EdPlunkett I'm in WPF. After more research I found how to convert the keys values from `Input` to `Forms` here https://stackoverflow.com/a/1153059/6806643 – Matt McManis Aug 06 '19 at 17:01
  • doesn't sound like it but maybe this is what you want? https://stackoverflow.com/a/25071604/3225 – kenny Aug 06 '19 at 18:39
  • Use this: `Enum.TryParse(e.Key.ToString(), out System.Windows.Forms.Keys winFormsKey)` – BionicCode Aug 06 '19 at 19:59

1 Answers1

0

You can use KeyInterop Class to convert WPF keys to WinForms and WinForms keys to WPF.

KeyInterop Class provides static methods to convert between Win32 Virtual-Keys and the WPF Key enumeration.

Sample:

private void btnDPad_L_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
    var wpfKey = e.Key;
    // Add System.Windows.Forms to references
    var winFormsKey = (Keys)KeyInterop.VirtualKeyFromKey(wpfKey);
    // TODO: ...
}
AmRo
  • 833
  • 1
  • 8
  • 19