简体   繁体   中英

Usage of User32.dll ToUnicodeEx function

On a system with a non-US keyboard / culture, I am receiving a Barcode from a scanner as keyboard input. The scanner can be set to different cultures. In my case it is set to en-US. In this case the system language and the barcode scanner language encoding are different.

I have declared this function to decode:

[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern int ToUnicodeEx(uint virtualKeyCode, uint scanCode, byte[] keyboardState, [Out, MarshalAs(UnmanagedType.LPWStr, SizeParamIndex = 4)] StringBuilder receivingBuffer, int bufferSize, uint flags, IntPtr dwhkl);

I use the method below to load a keyboard layout:

[DllImport("user32.dll")]
private static extern IntPtr LoadKeyboardLayout(string pwszKLID, uint Flags);

I use the method like below:

// loads the interpretation of the key into buf.
ToUnicodeEx(key, scankey, keyboardState, buf, 256, 0, LoadKeyboardLayout("00000409", 1));

My usage of the method works - the interpretation is correct - BUT I have a side effect that my system language setting is affected. Before method call it looks like this:

在此处输入图片说明

And after the method call it looks like this:

在此处输入图片说明

How can I fix my code so that my system's language is not affected?

I have tried to change flags parameter of the LoadKeyboardLayout to 0, but then ToUnicodeEx uses the system language, not the loaded en-US.

I'm sure that almost four years later you've either solved this or no longer care. I'll put the answer here in case someone else comes across this, though.

The last parameter of LoadKeyboardLayout is dwFlags . You gave it 1 , which is equivalent to KLF_ACTIVATE , or "load this bad boy up and make it my keyboard!"

You want to call it with 0 , which tells it to just load the layout, give you a handle (IntPtr) to it, and do nothing else.

I'm sorry I couldn't help you back when you posted this. :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM