.NET Framework Developer Center >
.NET Development Forums
>
Windows Presentation Foundation (WPF)
>
How to convert Form keys to Wpf Keys?
How to convert Form keys to Wpf Keys?
- hi
I'm Using Key Hooking Mechanism In wpf(http://www.codeproject.com/KB/cs/globalhook.aspx)
But in the above lind they use forms keys. But i want to convert it to Wpf. Here the problem is Forms keys contains 0 to 255 and some special Enum Members but in System.Windows.Input.Key contains only 0-171 Enum me members. If i Press above 171 Enum key it will through the exception. How can I Convert Form Keys to Wpf Keys? or any one one can give me Wpf Version Of the UserActivityHook
in the below link
http://www.koders.com/csharp/fid477E4BD57EA637D92D19A65FEF3E160B4C7C139F.aspx?s=textbox
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... 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
- What to do for missing Keys?
- 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 - 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

