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/ssda/p/10082709.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值