我在WPF中開發應用程序,但是一些組件是用WinForms編寫的。我不想讓這些組件從WPF部件拉出關鍵手勢並將它們轉換爲Keys枚舉(用於WinForms)。如何將'System.Windows.Input.Key'轉換爲'System.Windows.Forms.Keys'?
是否有內置轉換器? (可能不是) 你知道「比大開關容易嗎」的方法嗎?
我在WPF中開發應用程序,但是一些組件是用WinForms編寫的。我不想讓這些組件從WPF部件拉出關鍵手勢並將它們轉換爲Keys枚舉(用於WinForms)。如何將'System.Windows.Input.Key'轉換爲'System.Windows.Forms.Keys'?
是否有內置轉換器? (可能不是) 你知道「比大開關容易嗎」的方法嗎?
Keys formsKey = ...;
Key wpfKey = ...;
wpfKey = KeyInterop.KeyFromVirtualKey((int)formsKey);
formsKey = (Keys)KeyInterop.VirtualKeyFromKey(wpfKey);
KeyInterop class的是「鍵,」加上Windows窗體Keys
枚舉具有相同的整數值作爲贏32個虛擬鍵碼的事實。
如果要轉換改性劑,使用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);
萬一人蒸餾器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;
}
}
謝謝。太棒了。但是我怎樣才能轉換修飾符? – 2009-07-20 11:58:08