C# WinForms 应用程序的表单上有一个列表框。 ListBox 窗口句柄被传递到旧版 Win32 DLL,该 DLL 使用 SendMessage(hWnd,LB_ADDSTRING...) 将项目添加到列表框。这些字符串在运行时出现在列表框中,但 listbox.Items.Count 为 0,并且无法使用 listbox.Items[x].ToString() 访问单个项目
您需要在 C# 应用程序中做什么才能让它意识到这些字符串位于其列表中,因此应该反射(reflect)在 Items.Count 中,并且可以使用 Items[x] 进行访问?
最佳答案
创建ListBox
的子类,覆盖WndProc
,监听LB_ADDSTRING
消息(值= 0x180),防止这些消息被正常处理而是将它们包含的数据添加到 Items
集合中。尚未测试此代码,但它应该足够接近您的需要:
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
public class LegacyListBox : ListBox
{
private const int LB_ADDSTRING = 0x180;
public LegacyListBox() { }
protected override void WndProc(ref Message m)
{
if (m.Msg == LB_ADDSTRING)
{
Items.Add(Marshal.PtrToStringUni(m.LParam));
// prevent base class from handling this message
return;
}
base.WndProc(ref m);
}
}
关于c# - 使用 lb_addstring 添加到 C# 列表框的项目不会影响 items.count,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13000762/