2009-07-20 19 views

Respuesta

52
Keys formsKey = ...; 
Key wpfKey = ...; 
wpfKey = KeyInterop.KeyFromVirtualKey((int)formsKey); 
formsKey = (Keys)KeyInterop.VirtualKeyFromKey(wpfKey); 

El KeyInterop class es la "clave", además del hecho de que el Windows Forms Keys enumeración tiene los mismos valores enteros como los códigos de teclas virtuales Win 32.

+2

Gracias. Eso es realmente genial. ¿Pero cómo puedo convertir modificadores? –

0

Si desea convertir modificadores, utilice el SystemKey si usted está buscando en una KeyEventArgs:

System.Windows.Input.KeyEventArgs args; 
System.Windows.Input.Key wpfKey= args.Key == Key.System ? args.SystemKey : args.Key; 
formsKey = (System.Windows.Forms.Keys)KeyInterop.VirtualKeyFromKey(wpfKey); 
1

Sólo en caso de personas aún se encuentran con el problema modificador de 7 años después, aquí está mi solución que funcionó hasta el momento :

public static class KeyEventExts 
{ 
    public static System.Windows.Forms.KeyEventArgs ToWinforms(this System.Windows.Input.KeyEventArgs keyEventArgs) 
    { 
     // So far this ternary remained pointless, might be useful in some very specific cases though 
     var wpfKey = keyEventArgs.Key == System.Windows.Input.Key.System ? keyEventArgs.SystemKey : keyEventArgs.Key; 
     var winformModifiers = keyEventArgs.KeyboardDevice.Modifiers.ToWinforms(); 
     var winformKeys = (System.Windows.Forms.Keys)System.Windows.Input.KeyInterop.VirtualKeyFromKey(wpfKey); 
     return new System.Windows.Forms.KeyEventArgs(winformKeys | winformModifiers); 
    } 

    public static System.Windows.Forms.Keys ToWinforms(this System.Windows.Input.ModifierKeys modifier) 
    { 
     var retVal = System.Windows.Forms.Keys.None; 
     if(modifier.HasFlag(System.Windows.Input.ModifierKeys.Alt)) 
     { 
      retVal |= System.Windows.Forms.Keys.Alt; 
     } 
     if (modifier.HasFlag(System.Windows.Input.ModifierKeys.Control)) 
     { 
      retVal |= System.Windows.Forms.Keys.Control; 
     } 
     if (modifier.HasFlag(System.Windows.Input.ModifierKeys.None)) 
     { 
      // Pointless I know 
      retVal |= System.Windows.Forms.Keys.None; 
     } 
     if (modifier.HasFlag(System.Windows.Input.ModifierKeys.Shift)) 
     { 
      retVal |= System.Windows.Forms.Keys.Shift; 
     } 
     if (modifier.HasFlag(System.Windows.Input.ModifierKeys.Windows)) 
     { 
      // Not supported lel 
     } 
     return retVal; 
    } 
} 
Cuestiones relacionadas