c# - 使用 lb_addstring 添加到 C# 列表框的项目不会影响 items.count

标签 c# listbox

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/

相关文章:

javascript - 获取客户的一些身份信息

c# - Xamarin 动态加载本地化文件

c# - 如何刷新Windows8应用程序中的页面和内容

c# - 在 WPF ListBox 中隐藏空组

c# - 根据 OnKeyUp 的文本框过滤 ListBox 项目?

c# - 使用 MediatR 执行 API 方法时出现错误

c# - NHibernate QueryOver 按集合过滤

c# - 通过单击背景在 ListBox 中选择一个 CheckBox

asp.net - 数据绑定(bind)列表框和设置 css 类

python - Tkinter 文本小部件比任何其他带有网格的小部件更宽