CB_SELECTSTRING不适用于日语项目

问题描述 投票:2回答:2
 [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.");
 }

组合图片:ComboBox containing japanese item

我想从组合框中获取日文项目“英语”的索引,但它总是使用与上述英语项目相同的代码给出索引“ -1”,它为我提供正确的索引,而另外需要正确获取日文项目索引。

c# winforms winapi automation pinvoke
2个回答
2
投票

根据docsCB_SELECTSTRING消息的参数为:

  • wParam:要搜索的第一个项目之前的项目的从零开始的索引...如果wParam为-1,则从头开始搜索整个列表。

  • lParam:指向以空字符结尾的字符串的指针,该字符串包含要搜索的字符。搜索不区分大小写,因此此字符串可以包含大写和小写字母的任意组合。

因此您应该从SendMessage中为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)

传递-1(而不是null)作为从头开始搜索的第一个参数。


0
投票

证明关键部分是CharSetCharSet

您的旧代码也可以工作,只需进行简单的修改:

[DllImport]

[DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern int SendMessage(IntPtr hWnd, int msg, string wParam, string lParam); 的默认值为CharSet。您可以将其设置为AnsiAuto,这两个值大多数时候都对应于UTF-16,在Linux上UnicodeAuto,请参见UTF-8

完整示例:

Charsets and Marshalling
© www.soinside.com 2019 - 2024. All rights reserved.