I am using the System.Diagnostics.Process Namespace in C# to start a system process, sometimes this new created process won't start properly, in these cases Windows shows me an alert window giving information about the failed process. I need a way to close (kill) this alert window programatically. I tried the following code but it doesn't work, because the alert window won't appear in the Process.GetProcesses() list.
foreach (Process procR in Process.GetProcesses()) { if (procR.MainWindowTitle.StartsWith("alert window text")) { procR.Kill(); continue; } }
I will appreciate any help on this. Thanks!
UPDATE: Just wanted to let you know that this example worked for me. Thank you very much. Below there is some code that could help someone else. The code was tested with Visual Studio 2008, you still need a winform and a button to make it work.using System; using System.Windows.Forms; using System.Runtime.InteropServices; /* More info about Window Classes at http://msdn.microsoft.com/en-us/library/ms633574(VS.85).aspx */ namespace WindowsFormsApplication1 { public partial class Form1 : Form { const uint WM_CLOSE = 0x10; [DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)] private static extern IntPtr FindWindow(string lpClassName, string lpWindowName); [DllImport("user32.dll", CharSet = CharSet.Auto)] static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam); 开发者_JAVA百科public Form1() { InitializeComponent(); } /* This event will silently kill any alert dialog box */ private void button2_Click(object sender, EventArgs e) { string dialogBoxText = "Rename File"; /* Windows would give you this alert when you try to set to files to the same name */ IntPtr hwnd = FindWindow("#32770", dialogBoxText); SendMessage(hwnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero); } } }
You can try using PInvoke to call FindWindow() API by parameters, such as name and/or window class, and then PInvoke the SendMessage(window, WM_CLOSE, 0, 0) API to close it.
Correct, because the the alert window (which is properly called a message box) is not the application's main window.
I think you'd have to examine the process' windows using EnumThreadWindows and GetWindowText.
精彩评论