【发布时间】: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