C#代码获取另一程序的错误提示,并关闭窗口。

A程序报错弹框如下:

B程序捕捉到此错误消息,并关闭。B程序核心代码如下。 

private void timer_Click(object sender, EventArgs e)
{
    //查找MessageBox的弹出窗口,注意对应标题
    IntPtr ptr = FindWindow(null, "提示");
    if (ptr != IntPtr.Zero)
    {
        EnumChildWindows(ptr.ToInt32(), callBackEnumChildWindows, 0);
        //int length = GetWindowTextLength(ptr);
        //StringBuilder windowName = new StringBuilder(length + 1);
        //GetWindowText(ptr.ToInt32(), windowName, windowName.Capacity);                
        PostMessage(ptr, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);//查找到弹窗则关闭它
    }
}

#region api
[DllImport("user32.dll", EntryPoint = "FindWindow", CharSet = CharSet.Auto)]
private extern static IntPtr FindWindow(string lpClassName, string lpWindowName);

[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern int PostMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);

public const int WM_CLOSE = 0x10;

[DllImport("user32.dll")]
public static extern int EnumChildWindows(int hWndParent, CallBack lpfn, int lParam);

/// <summary>
/// 子窗口回调函数代理
/// </summary>
public static CallBack callBackEnumChildWindows = new CallBack(ChildWindowProcess);

/// <summary>
/// 子窗口回调处理函数
/// </summary>
/// <param name="hwnd"></param>
/// <param name="lParam"></param>
/// <returns></returns>
public static bool ChildWindowProcess(int hwnd, int lParam)
{
    StringBuilder text = new StringBuilder(200);
    int len;
    len = GetWindowText(hwnd, text, 200);
    if (len > 0)
    {
        if (text.ToString().Contains("未将对象引用"))
        {
            //找到错误
        }
    }
    return true;
}
[DllImport("user32.dll")]
public static extern int GetWindowText(int hWnd, StringBuilder lpString, int nMaxCount);

/// <summary>
/// 回调函数代理
/// </summary>
public delegate bool CallBack(int hwnd, int lParam);

[DllImport("user32.dll")]
public static extern int GetWindowTextLength(IntPtr hWnd);
#endregion
原文地址:https://www.cnblogs.com/linmilove/p/10082709.html