草庐IT

c# - 阻止进程创建 MessageBox

coder 2024-06-11 原文

我在我们的应用程序中使用的系统有问题:有时,当我们向该系统询问数据时,他会弹出一个 MessageBox 来告诉我们类似这样的信息:“我无法检索您的数据,要搜索的数据太多了”。

这个问题是用户可能无法看到或关闭弹出窗口,因此这会阻止整个应用程序(解释为什么用户无法关闭/看到弹出窗口会花费太多时间并且偏离主题,这很糟糕但我们必须处理它)。

因此,作为一个临时解决方案,我想阻止这个特定进程创建 MessageBox。

我在网上寻找解决方案并找到了关于 CBTProc 的信息这似乎提供了一种对特定 Windows 事件(进程创建窗口的请求)作出 react 并指示操作系统阻止该请求的方法。

这是要走的路吗?

我测试了SetWinEventHook检测请求创建窗口和 DestroyWindow 的进程销毁窗口:

public class PopupWatchdog {

    #region constructor
    public PopupWatchdog() {
        SetWinEventHook(
            EVENT_OBJECT_CREATED,
            EVENT_OBJECT_CREATED,
            IntPtr.Zero,
            HookCallback,
            0, //id process
            0, //id thread
            WINEVENT_OUTOFCONTEXT
        );
    }
    #endregion

    #region functions
    private static void HookCallback(IntPtr hWinEventHook, int iEvent, IntPtr hWnd, int idObject, int idChild, int dwEventThread, int dwmsEventTime) {
        Console.WriteLine("window {0} requests creating an object, trying to destroy it...", idChild);
        DestroyWindow(hWnd);
    }

    [DllImport("user32.dll", SetLastError = true)]
    private static extern IntPtr SetWinEventHook(int eventMin, int eventMax, IntPtr hmodWinEventProc, HookProc lpfnWinEventProc, int idProcess, int idThread, int dwflags);

    [DllImport("user32.dll")]
    private static extern bool DestroyWindow(IntPtr hWnd);
    #endregion

    #region events

    #endregion

    #region variables
    #region const
    private const int EVENT_OBJECT_CREATED = 0x8000;
    private const int WINEVENT_OUTOFCONTEXT = 0;
    #endregion
    private delegate void HookProc(
        IntPtr hWinEventHook,
        int iEvent,
        IntPtr hWnd,
        int idObject, 
        int idChild,
        int dwEventThread, 
        int dwmsEventTime
    );
    #endregion
}

DestroyWindow 不能像 msdn 文档所说的那样用于销毁另一个线程创建的窗口,这是不稳定的。所以我的测试没有成功。我该如何解决这个问题?

我可能犯了错误,我不太了解 Windows api,只是听说了 CBTProc。

更新

我根据@DavidHeffernan 和@AlexK 的建议更改了代码,并且有效:

public class BlockingPopupWatchdog {
    #region ctor
    public BlockingPopupWatchdog(int processId) {
        _processId = processId;
    }
    #endregion

    #region functions
    internal bool Hook() {
        if (_hookId != IntPtr.Zero) {
            Unhook();
        }
        _hookId = SetWinEventHook(
            EVENT_OBJECT_CREATED,
            EVENT_OBJECT_CREATED,
            IntPtr.Zero,
            _hook,
            _processId, //id process
            0, //id thread
            WINEVENT_OUTOFCONTEXT
        );

        if (_hookId == IntPtr.Zero) {
            Logger.Log(String.Format("Error {0} while hooking", Marshal.GetLastWin32Error()), EventTypes.WARNING);
            return false;
        }
        return true;
    }

    internal bool Unhook() {
        if (_hookId == IntPtr.Zero) return false;
        if (!UnhookWinEvent(_hookId)) {
            Logger.Log(String.Format("Error {0} while unhooking", Marshal.GetLastWin32Error()), EventTypes.WARNING);
            return false;
        }
        return true;
    }
    private static void HookCallback(IntPtr hWinEventHook, int iEvent, IntPtr hWnd, int idObject, int idChild, int dwEventThread, int dwmsEventTime) {
        if (hWnd == IntPtr.Zero) return;

        try {
            AutomationElement elem = AutomationElement.FromHandle(hWnd);
            if (elem == null || !elem.Current.ClassName.Equals(MESSAGEBOX_CLASS_NAME)) {
                return;
            }

            object pattern;
            if (!elem.TryGetCurrentPattern(WindowPattern.Pattern, out pattern)) return;

            WindowPattern window = (WindowPattern)pattern;
            if (window.Current.WindowInteractionState == WindowInteractionState.ReadyForUserInteraction) {
                window.Close();
            }
        } catch (Exception e) {
            Console.WriteLine(e);
        }
    }
    [DllImport("user32.dll", SetLastError = true)]
    private static extern IntPtr SetWinEventHook(int eventMin, int eventMax, IntPtr hmodWinEventProc, HookProc lpfnWinEventProc, int idProcess, int idThread, int dwflags);

    [DllImport("user32.dll", SetLastError = true)]
    private static extern bool UnhookWinEvent(IntPtr hWinEventHook);
    #endregion

    #region variables
    #region const
    private const String MESSAGEBOX_CLASS_NAME = "#32770";
    private const int EVENT_OBJECT_CREATED = 0x8000;
    private const int WINEVENT_OUTOFCONTEXT = 0;
    #endregion

    private delegate void HookProc(
        IntPtr hWinEventHook,
        int iEvent,
        IntPtr hWnd,
        int idObject,
        int idChild,
        int dwEventThread,
        int dwmsEventTime
    );

    private static readonly HookProc _hook = HookCallback;
    private IntPtr _hookId;
    private readonly int _processId;
    #endregion
}

最佳答案

感谢 DavidHefferman 和 AlexK。这是实现我想要的解决方案。

使用 WinApi:

public class BlockingPopupWatchdog {
    #region ctor
    public BlockingPopupWatchdog(int processId) {
        _processId = processId;
    }
    #endregion

    #region functions
    internal bool Hook() {
        if (_hookId != IntPtr.Zero) {
            Unhook();
        }
        _hookId = SetWinEventHook(
            EVENT_OBJECT_CREATED,
            EVENT_OBJECT_CREATED,
            IntPtr.Zero,
            _hook,
            _processId, //id process
            0, //id thread
            WINEVENT_OUTOFCONTEXT
        );

        if (_hookId == IntPtr.Zero) {
            Logger.Log(String.Format("Error {0} while hooking", Marshal.GetLastWin32Error()), EventTypes.WARNING);
            return false;
        }
        return true;
    }

    internal bool Unhook() {
        if (_hookId == IntPtr.Zero) return false;
        if (!UnhookWinEvent(_hookId)) {
            Logger.Log(String.Format("Error {0} while unhooking", Marshal.GetLastWin32Error()), EventTypes.WARNING);
            return false;
        }
        return true;
    }
    private static void HookCallback(IntPtr hWinEventHook, int iEvent, IntPtr hWnd, int idObject, int idChild, int dwEventThread, int dwmsEventTime) {
        if (hWnd == IntPtr.Zero) return;

        try {
            AutomationElement elem = AutomationElement.FromHandle(hWnd);
            if (elem == null || !elem.Current.ClassName.Equals(MESSAGEBOX_CLASS_NAME)) {
                return;
            }

            object pattern;
            if (!elem.TryGetCurrentPattern(WindowPattern.Pattern, out pattern)) return;

            WindowPattern window = (WindowPattern)pattern;
            if (window.Current.WindowInteractionState == WindowInteractionState.ReadyForUserInteraction) {
                window.Close();
            }
        } catch (Exception e) {
            Console.WriteLine(e);
        }
    }
    [DllImport("user32.dll", SetLastError = true)]
    private static extern IntPtr SetWinEventHook(int eventMin, int eventMax, IntPtr hmodWinEventProc, HookProc lpfnWinEventProc, int idProcess, int idThread, int dwflags);

    [DllImport("user32.dll", SetLastError = true)]
    private static extern bool UnhookWinEvent(IntPtr hWinEventHook);
    #endregion

    #region variables
    #region const
    private const String MESSAGEBOX_CLASS_NAME = "#32770";
    private const int EVENT_OBJECT_CREATED = 0x8000;
    private const int WINEVENT_OUTOFCONTEXT = 0;
    #endregion

    private delegate void HookProc(
        IntPtr hWinEventHook,
        int iEvent,
        IntPtr hWnd,
        int idObject,
        int idChild,
        int dwEventThread,
        int dwmsEventTime
    );

    private static readonly HookProc _hook = HookCallback;
    private IntPtr _hookId;
    private readonly int _processId;
    #endregion
}

以及使用 UIAutomation 的解决方案:

private AutomationElement _watchedElement;
private void PopupOpenedHandler(Object sender, AutomationEventArgs args) {
    var element = sender as AutomationElement;
    if (element == null || !element.Current.ClassName.Equals(MESSAGEBOX_CLASS_NAME)) {
        return;
    }

    object pattern;
    if (!element.TryGetCurrentPattern(WindowPattern.Pattern, out pattern)) return;

    WindowPattern window = (WindowPattern)pattern;
    if (window.Current.WindowInteractionState == WindowInteractionState.ReadyForUserInteraction) {
        window.Close();
    }
}

internal bool Hook() {
    Process p = Process.GetProcessById(_processId);
    IntPtr wHnd = p.MainWindowHandle;
    if (wHnd != IntPtr.Zero) {
        _watchedElement = AutomationElement.FromHandle(wHnd);
        Automation.AddAutomationEventHandler (
            WindowPattern.WindowOpenedEvent,
            _watchedElement,
            TreeScope.Descendants,
            PopupOpenedHandler
        );
        return true;
    }
    return false;
}


internal bool Unhook() {
    if (_watchedElement == null) return false;
    Automation.RemoveAutomationEventHandler(WindowPattern.WindowOpenedEvent, _watchedElement, PopupOpenedHandler);
    return true;
}

关于c# - 阻止进程创建 MessageBox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35845846/

有关c# - 阻止进程创建 MessageBox的更多相关文章

  1. ruby - 如何在 Ruby 中顺序创建 PI - 2

    出于纯粹的兴趣,我很好奇如何按顺序创建PI,而不是在过程结果之后生成数字,而是让数字在过程本身生成时显示。如果是这种情况,那么数字可以自行产生,我可以对以前看到的数字实现垃圾收集,从而创建一个无限系列。结果只是在Pi系列之后每秒生成一个数字。这是我通过互联网筛选的结果:这是流行的计算机友好算法,类机器算法:defarccot(x,unity)xpow=unity/xn=1sign=1sum=0loopdoterm=xpow/nbreakifterm==0sum+=sign*(xpow/n)xpow/=x*xn+=2sign=-signendsumenddefcalc_pi(digits

  2. ruby - 在 Ruby 程序执行时阻止 Windows 7 PC 进入休眠状态 - 2

    我需要在客户计算机上运行Ruby应用程序。通常需要几天才能完成(复制大备份文件)。问题是如果启用sleep,它会中断应用程序。否则,计算机将持续运行数周,直到我下次访问为止。有什么方法可以防止执行期间休眠并让Windows在执行后休眠吗?欢迎任何疯狂的想法;-) 最佳答案 Here建议使用SetThreadExecutionStateWinAPI函数,使应用程序能够通知系统它正在使用中,从而防止系统在应用程序运行时进入休眠状态或关闭显示。像这样的东西:require'Win32API'ES_AWAYMODE_REQUIRED=0x0

  3. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  4. ruby - 使用 Vim Rails,您可以创建一个新的迁移文件并一次性打开它吗? - 2

    使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta

  5. ruby-on-rails - 无法使用 Rails 3.2 创建插件? - 2

    我对最新版本的Rails有疑问。我创建了一个新应用程序(railsnewMyProject),但我没有脚本/生成,只有脚本/rails,当我输入ruby./script/railsgeneratepluginmy_plugin"Couldnotfindgeneratorplugin.".你知道如何生成插件模板吗?没有这个命令可以创建插件吗?PS:我正在使用Rails3.2.1和ruby​​1.8.7[universal-darwin11.0] 最佳答案 随着Rails3.2.0的发布,插件生成器已经被移除。查看变更日志here.现在

  6. ruby - 在 jRuby 中使用 'fork' 生成进程的替代方案? - 2

    在MRIRuby中我可以这样做:deftransferinternal_server=self.init_serverpid=forkdointernal_server.runend#Maketheserverprocessrunindependently.Process.detach(pid)internal_client=self.init_client#Dootherstuffwithconnectingtointernal_server...internal_client.post('somedata')ensure#KillserverProcess.kill('KILL',

  7. ruby - 如何使用 RSpec::Core::RakeTask 创建 RSpec Rake 任务? - 2

    如何使用RSpec::Core::RakeTask初始化RSpecRake任务?require'rspec/core/rake_task'RSpec::Core::RakeTask.newdo|t|#whatdoIputinhere?endInitialize函数记录在http://rubydoc.info/github/rspec/rspec-core/RSpec/Core/RakeTask#initialize-instance_method没有很好的记录;它只是说:-(RakeTask)initialize(*args,&task_block)AnewinstanceofRake

  8. ruby - 通过 ruby​​ 进程共享变量 - 2

    我正在编写一个gem,我必须在其中fork两个启动两个webrick服务器的进程。我想通过基类的类方法启动这个服务器,因为应该只有这两个服务器在运行,而不是多个。在运行时,我想调用这两个服务器上的一些方法来更改变量。我的问题是,我无法通过基类的类方法访问fork的实例变量。此外,我不能在我的基类中使用线程,因为在幕后我正在使用另一个不是线程安全的库。所以我必须将每个服务器派生到它自己的进程。我用类变量试过了,比如@@server。但是当我试图通过基类访问这个变量时,它是nil。我读到在Ruby中不可能在分支之间共享类变量,对吗?那么,还有其他解决办法吗?我考虑过使用单例,但我不确定这是

  9. ruby - 为什么 SecureRandom.uuid 创建一个唯一的字符串? - 2

    关闭。这个问题需要detailsorclarity.它目前不接受答案。想改进这个问题吗?通过editingthispost添加细节并澄清问题.关闭8年前。Improvethisquestion为什么SecureRandom.uuid创建一个唯一的字符串?SecureRandom.uuid#=>"35cb4e30-54e1-49f9-b5ce-4134799eb2c0"SecureRandom.uuid方法创建的字符串从不重复?

  10. ruby - 有人可以帮助解释类创建的 post_initialize 回调吗 (Sandi Metz) - 2

    我正在阅读SandiMetz的POODR,并且遇到了一个我不太了解的编码原则。这是代码:classBicycleattr_reader:size,:chain,:tire_sizedefinitialize(args={})@size=args[:size]||1@chain=args[:chain]||2@tire_size=args[:tire_size]||3post_initialize(args)endendclassMountainBike此代码将为其各自的属性输出1,2,3,4,5。我不明白的是查找方法。当一辆山地自行车被实例化时,因为它没有自己的initialize方法

随机推荐