Ask a questionAsk a question
 

Proposed AnswerHow to convert Form keys to Wpf Keys?

All Replies

  • Monday, June 30, 2008 4:59 PMMatt Galbraith - MSFTModeratorUsers MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Has Code
    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...  
                try 
                {  
                    return (System.Windows.Input.Key)Enum.Parse(typeof(System.Windows.Input.Key), inputKey.ToString());  
                }  
                catch 
                {  
                    // There wasn't a direct mapping...    
                    return System.Windows.Input.Key.None;  
                }  
            } 



    Hope this helps,
    Matt
    SDET : Deployment/Hosting
    • Unmarked As Answer byAnandakumar.R Tuesday, July 15, 2008 1:48 PM
    • Marked As Answer byMarco Zhou Friday, July 04, 2008 10:25 AM
    •  
  • Tuesday, July 15, 2008 1:47 PMAnandakumar.R Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    What to do for missing Keys?
  • Tuesday, August 12, 2008 11:00 PMMatt Galbraith - MSFTModeratorUsers MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    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.

    -Matt
    SDET : Deployment/Hosting
  • Monday, December 07, 2009 8:16 PMlevi.haskell Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Proposed Answer
    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);

    Regards,
     - Levi
    • Proposed As Answer bylevi.haskell Monday, December 07, 2009 8:16 PM
    •