How to convert Form keys to Wpf Keys? RRS feed

All replies

  • Sadly there's no direct cast there and there ARE two types of Key(s).  However, it's pretty simple to parse them and figure out if a mapping exists.  As noted below, if a member with the same identical name doesnt exist, it's simply a matter of placing special casing code  for that key instead of trying the Parse() operation.

            public static System.Windows.Input.Key WinformsToWPFKey(System.Windows.Forms.Keys inputKey)  
                // Put special case logic here if there's a key you need but doesn't map...  
                    return (System.Windows.Input.Key)Enum.Parse(typeof(System.Windows.Input.Key), inputKey.ToString());  
                    // There wasn't a direct mapping...    
                    return System.Windows.Input.Key.None;  

    Hope this helps,
    SDET : Deployment/Hosting
    • Marked as answer by Marco Zhou Friday, July 4, 2008 10:25 AM
    • Unmarked as answer by Anandakumar.R Tuesday, July 15, 2008 1:48 PM
    Monday, June 30, 2008 4:59 PM
  • What to do for missing Keys?
    Tuesday, July 15, 2008 1:47 PM
  • I believe I've already shown that above... if there ISN'T a direct mapping, you'll end up moving execution into the catch statement above.  Simply have a switch statement if you need to handle the translation of such keys, or simply return "None" as I have here.

    SDET : Deployment/Hosting
    Tuesday, August 12, 2008 11:00 PM
  • There is a function for that in System.Windows.Input.KeyInterop static class. Try:

    var inputKey = KeyInterop.KeyFromVirtualKey((int)formsKey);

    It works because System.Windows.Forms.Keys enumeration members and Win32 virtual key codes has the same numerical values (by design), while WPF's System.Windows.Input.Key do not (also by design).

    This will definitly work much faster than Matt's format-then-parse method. And probably more correct in corner cases, like when literal names of the same logical key might differ slightly in the two enums.

    Finally if you need to convert in the opposite direction use:

    var formsKey = (System.Windows.Forms.Keys)KeyInterop.VirtualKeyFromKey(inputKey);

     - Levi
    • Proposed as answer by Levi Haskell Monday, December 7, 2009 8:16 PM
    Monday, December 7, 2009 8:16 PM
  • what would be the WPF equivalent of



    (in case I don't want to reference System.Windows.Forms in my WPF app)




    Tuesday, October 18, 2011 6:24 PM