1

如果我将 MessageBox 显示为另一个进程的窗口模式,只要我的程序保持响应,它就可以正常工作。如果在 MessageBox 显示接收 MessageBox 的窗口时关闭或终止它,将被锁定(但仍然响应),并且必须通过任务管理器完成。

这是一个示例代码来演示:

using System;
using System.Windows.Forms;
using System.Diagnostics;
using System.Threading;

namespace TestMessageBox
{
    class Program
    {
        private WindowWrapper notepad;

        Program(IntPtr handle)
        { 
            notepad = new WindowWrapper(handle); 
        }

        static void Main(string[] args)
        {
            Process[] procs = Process.GetProcessesByName("notepad");
            if (procs.Length > 0)
            {
                Console.WriteLine("Notepad detected...");
                Program program = new Program(procs[0].MainWindowHandle);
                Thread thread = new Thread(new ThreadStart(program.ShowMessage));
                thread.IsBackground = true;
                thread.Start();
                Console.Write("Press any key to end the program and lock notepad...");
                Console.ReadKey();
            }
        }

        void ShowMessage()
        { 
            MessageBox.Show(notepad, "If this is open when the program ends\nit will lock up notepad..."); 
        }
    }

    /// <summary>
    /// Wrapper class so that we can return an IWin32Window given a hwnd
    /// </summary>
    public class WindowWrapper : System.Windows.Forms.IWin32Window
    {
        public WindowWrapper(IntPtr handle)
        { 
            _hwnd = handle; 
        }
        public IntPtr Handle
        { 
            get { return _hwnd; } 
        }
        private IntPtr _hwnd;
    }

}

如何避免这种情况?

4

1 回答 1

1

显示模式对话框的行为会禁用对话框的父窗口(在您的示例中为记事本窗口)。当模态对话框关闭时,父窗口会重新启用。

如果您的程序在重新启用窗口之前死机,则该窗口将永远不会重新启用 - 由显示对话框的线程来重新启用父级。(在您的示例中,它发生在MessageBox.Show()用户单击 OK 或其他任何内容之后。)

完成这项工作的唯一方法是拥有第二个进程,如果创建模态对话框的进程过早死亡,其职责是让事情恢复原状,但这太可怕了。而且它仍然不是万无一失的——如果观察者进程也死了怎么办?

于 2009-08-11T12:25:16.570 回答