clicking message box button using api
As a little bit of background: I am using code to change the values of a setup project - using envDTE.DTE. This works fine, but as a result of one of the values I am changing, a message box is raised - on which I need to click the "OK" button - also programatically.
I have set a timer to run every second which checks to see if the messagebox is open and if it is it clicks the OK button.
This is the code I'm using:
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern IntPtr SetActiveWindow(IntPtr hWnd);
private const uint BM_CLICK = 245;
public static void Timer_Tick(object sender, EventArgs Args)
{
IntPtr messageHandle = FindWindow("#32770", "Microsoft Visual Studio");
if (messageHandle.ToInt32() != 0)
{
IntPtr buttonHandle = FindWindowEx(messageHandle, IntPtr.Zero, "Button", "&Yes");
if (buttonHandle.ToInt32() != 0)
{
IntPtr sawResult;
sawResult=SetActiveWindow(buttonHandle);
if (sawResult.ToInt32() != 0)
{
SendMessage(buttonHandle, BM_CLICK, IntPtr.Zero, IntPtr.Zero);
} // if (sawResult.ToInt32() != 0)
} // if (buttonHandle.ToInt32() != 0)
} //if (messageHandle.ToInt32() != 0)
} //public static void Timer_Tick(object sender, EventArgs Args)
Sometimes this works fine, but sometimes it doesn't seem to be clicking the OK button.... Apparently BM_CLICK only works with the active window, so I tried using setActiveWindow to make sure that the messagebox was the active window, but this only works when the application itself is the active application. I think it's likely that because the program is running in code and not with a gui that it is not always the active application.
Any thoughts on how to get this to work?
thanks!

