Search code examples
c#winformswinapipinvokeselectedindexchanged

How do I make SelectedIndexChanged trigger when I change C# WinForms ComboBox.SelectedIndex using Win32 API and P/Invoke?


I have a WinForms C# application with a ComboBox that is subscribing to SelectedIndexChanged (or SelectionChangeCommitted) events. This works great when the selected item is changed the "normal way", but when I change it from another application using P/Invoke and Win32 API, then I don't get the events (but I can see the selected item changing). Does anybody know how I can solve this?

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!!!

Solution

  • I was able to get it to work by using the code posted by SteveWilkinson in the thread https://stackoverflow.com/a/8894386/2075678. I noticed that the handle for my ComboBox changed every time a new selection was made! I think this is because it was created in Visual Studio by Right-clicking on Project -> Add -> User Control... So for this particular ComboBox I also had to store the parent handle and each time I need to access the ComboBox handle I have to re-discover it using IntPtr GetParent(IntPtr hWnd).