zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    浏览器允许跨域运行字符串
    检查失败,<master>分支有过其他更新,请先在本地合并<master>分支的代码
    微信公众号开发点点滴滴
    手机上的软件开发应该
    见过写过最好的代码
    Prometheus之新版node_exporter监控主机设置
    Granfana设置邮件告警
    linux 中添加自己的库路径的方法 cannot open shared object file: No such file or directory
    C# this.Invoke()的作用与用法
    C#中this.Invoke()中委托的定义
  • 原文地址:https://www.cnblogs.com/linmilove/p/10082709.html
Copyright © 2011-2022 走看看