Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The correct solution is the <code>ToUnicode</code> WinAPI function:</p> <pre><code>[DllImport("user32.dll")] public static extern int ToUnicode(uint virtualKeyCode, uint scanCode, byte[] keyboardState, [Out, MarshalAs(UnmanagedType.LPWStr, SizeConst = 64)] StringBuilder receivingBuffer, int bufferSize, uint flags); </code></pre> <p>One way to wrap this into a sensible, convenient method would be:</p> <pre><code>static string GetCharsFromKeys(Keys keys, bool shift, bool altGr) { var buf = new StringBuilder(256); var keyboardState = new byte[256]; if (shift) keyboardState[(int) Keys.ShiftKey] = 0xff; if (altGr) { keyboardState[(int) Keys.ControlKey] = 0xff; keyboardState[(int) Keys.Menu] = 0xff; } WinAPI.ToUnicode((uint) keys, 0, keyboardState, buf, 256, 0); return buf.ToString(); } </code></pre> <p>Now we can retrieve characters and actually get the expected results:</p> <pre><code>Console.WriteLine(GetCharsFromKeys(Keys.E, false, false)); // prints e Console.WriteLine(GetCharsFromKeys(Keys.E, true, false)); // prints E // Assuming British keyboard layout: Console.WriteLine(GetCharsFromKeys(Keys.E, false, true)); // prints é Console.WriteLine(GetCharsFromKeys(Keys.E, true, true)); // prints É </code></pre> <p>It is also possible to use <a href="http://msdn.microsoft.com/en-us/library/ms646322%28VS.85%29.aspx" rel="noreferrer"><code>ToUnicodeEx</code></a> to retrieve the characters for a keyboard layout that is not the currently active one. The signature is the same except for one extra parameter, the input locale ID, which can be retrieved using the <a href="http://msdn.microsoft.com/en-us/library/ms646305%28v=VS.85%29.aspx" rel="noreferrer"><code>LoadKeyboardLayout</code></a> function.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload