Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using PostMessage to send Unicode characters

Tags:

c#

unicode

user32

I am using PostMessage to send input to a flash object in another application. It works fine until I try to send a unicode character. In this example:

Michael’s Book

The apostrophe is not really that, it is not an ASCII 39, but rather a unicode U+2019. By the time it is sent across 1 character at a time, it is lost as a unicode value and lands as the raw characters making up the unicode

Michael’s Book

If I copy and paste into that window it moves fine, and if I load a text file into that window it loads fine. So the receiving window is able to receive unicode, but the way I am sending it must not be correct. Any help would be greatly appreciated.

  private void SendKeysToForm(string Message)
    {
        for (int i = 0; i < Message.Length; i++)
        {
            PostMessage(hwnd, WM_CHAR, (IntPtr)Message[i], IntPtr.Zero);
        }
    }
like image 319
Vincent James Avatar asked Oct 23 '25 00:10

Vincent James


1 Answers

Per the MSDN documentation, to send Unicode, you need to use PostMessageW.

It's the same method signature, just import the name PostMessageW and execute that.

UPDATE

As Hans very well stated, an even better approach would be to set the CharSet of the DllImport:

[DllImport("user32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
private static extern bool PostMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);

This should cause the framework to ultimately import PostMessageW.

Thanks a lot Hans!

like image 98
Mike Perrenoud Avatar answered Oct 26 '25 02:10

Mike Perrenoud



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!