2009-07-20 50 views

回答

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

KeyInterop class的是「鍵,」加上Windows窗體Keys枚舉具有相同的整數值作爲贏32個虛擬鍵碼的事實。

+2

謝謝。太棒了。但是我怎樣才能轉換修飾符? – 2009-07-20 11:58:08

0

如果要轉換改性劑,使用SystemKey,如果你正在尋找一個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

萬一人蒸餾器7年之後遇到的修改問題,這是我的解決方案,到目前爲止,工作:

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; 
    } 
} 
相關問題