Search code examples
c#unicodeuser32

Using PostMessage to send Unicode characters


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);
        }
    }

Solution

  • 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!