4

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);
        }
    }
Vincent James
  • 1,120
  • 3
  • 16
  • 27
  • 1
    Maybe WM_UNICHAR will work better. Depends, Adobe software is, erm, special. – Hans Passant Jul 06 '16 at 12:29
  • Why are you sending the character as `IntPtr` instead of int ? – Panagiotis Kanavos Jul 06 '16 at 12:30
  • @HansPassant [WM_CHAR](https://msdn.microsoft.com/en-us/library/windows/desktop/ms646276(v=vs.85).aspx) uses UTF-16-bit, `WM_UNICHAR` is for UTF-32 – Panagiotis Kanavos Jul 06 '16 at 12:31
  • 1
    That's not the point. The key is whether the window was created with CreateWindowExA() or CreateWindowsExW(). Visible in Spy++ btw. If you want an Ansi window to still eat a Unicode character then WM_UNICHAR might work. But sure, @Mike might well have correctly guessed that PostMessage wasn't declared correctly. – Hans Passant Jul 06 '16 at 12:48

1 Answers1

6

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!

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
Mike Perrenoud
  • 66,820
  • 29
  • 157
  • 232