Search code examples
c#winformswinapiautomationpinvoke

CB_SELECTSTRING is not working for Japanese item


 [DllImport("user32.dll")]
 public static extern int SendMessage(IntPtr hWnd, int msg, string wParam, string lParam);

 Private void GetSlecteITemIdex()
 {
       int _ComBoxHandle = System.Windows.Automation.AutomationElement.Current.NativeWindowHandle;
       int l_GETSelectedItem1 = SendMessage((IntPtr)l_ComBoxHandle, CB_SELECTSTRING, null, "英語");
         if (l_GETSelectedItem1 == -1)
                throw new Exception("Item not found.");
 }

Combo Image: ComboBox containing japanese item

I want to get index of japanese item "英語" from combobox but its always giving index "-1" using above code same for english items its giving me correct index what additionally need to do get Japanese item index correctly.


Solution

  • According to the docs, the arguments for a CB_SELECTSTRING message are:

    • wParam: The zero-based index of the item preceding the first item to be searched... If wParam is -1, the entire list is searched from the beginning.

    • lParam: A pointer to the null-terminated string that contains the characters for which to search. The search is not case sensitive, so this string can contain any combination of uppercase and lowercase letters.

    Thus you should choose the following declaration for SendMessage from https://www.pinvoke.net/default.aspx/user32.sendmessage:

    [DllImport("user32.dll", CharSet = CharSet.Auto)] 
    public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, int wParam, [MarshalAs(UnmanagedType.LPWStr)] string lParam)
    

    Pass -1 (rather than null) for the first argument to search from the beginning.

    (Note that CharSet = CharSet.Unicode may be chosen also. As explained in Charsets and marshaling, Auto and Unicode both cause strings to be marshalled to wchar_t (UTF-16) on Windows and char16_t (UTF-16) on .NET Core 2.2 and earlier on Unix; they differ only on .NET Core 3.0 and later and Mono on Unix where Auto marshals strings to char (UTF-8).)