【问题标题】:How do I make SelectedIndexChanged trigger when I change C# WinForms ComboBox.SelectedIndex using Win32 API and P/Invoke?当我使用 Win32 API 和 P/Invoke 更改 C# WinForms ComboBox.SelectedIndex 时,如何触发 SelectedIndexChanged?
【发布时间】:2021-07-28 14:39:27
【问题描述】:

我有一个 WinForms C# 应用程序,它带有一个订阅 SelectedIndexChanged(或 SelectionChangeCommitted)事件的 ComboBox。这在以“正常方式”更改所选项目时效果很好,但是当我使用 P/Invoke 和 Win32 API 从另一个应用程序更改它时,我没有收到事件(但我可以看到所选项目发生变化)。有谁知道我该如何解决这个问题?

private const int CB_SETCURSEL = 0x14E;
[DllImport("user32.dll")]
public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, int wParam, ref int lParam);

int lParam = 0;
SendMessage(hWnd, CB_SETCURSEL, 5, ref lParam); // Select item 5 in ComboBox. Doesn't trigger 
                                                // SelectedIndexChanged event in the other application!!!

【问题讨论】:

  • 从另一个进程执行此操作的“正常”方法是使用UI Automation
  • 如果您只需要这个,CB_SETCURSEL 可以正常工作。你的 SendMessage 声明有误,改成int SendMessage(IntPtr hWnd, uint uMsg, int wParam, int lParam),然后:int result = SendMessage(hWnd, CB_SETCURSEL, 5, 0);。假设你得到了正确的句柄并且你的 ComboBox 的列表包含至少 6 个项目。检查result 的值——否则,如果您确实需要自动化其他应用程序,当然 UI 自动化是首选工具。

标签: c# winforms winapi pinvoke selectedindexchanged


【解决方案1】:

我能够通过使用 SteveWilkinson 在线程 https://stackoverflow.com/a/8894386/2075678 中发布的代码来使其工作。我注意到每次做出新选择时,我的 ComboBox 的句柄都会发生变化!我认为这是因为它是通过右键单击 Project -> Add -> User Control 在 Visual Studio 中创建的...所以对于这个特定的 ComboBox 我还必须存储父句柄,并且每次我需要访问 ComboBox 句柄我必须使用 IntPtr GetParent(IntPtr hWnd) 重新发现它。

【讨论】:

    猜你喜欢
    • 2013-05-31
    • 1970-01-01
    • 1970-01-01
    • 2012-02-19
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多