1

我需要一个具有以下行为的 Windows 窗体应用程序:

  1. 当程序从资源管理器运行时(例如),无需任何控制台即可工作。
  2. Console.WriteLine()从命令行运行程序时重定向所有文本(因此程序必须将所有输出重定向到父控制台)

为此,适用以下代码:

[System.Runtime.InteropServices.DllImport("kernel32.dll")]
private static extern bool AttachConsole(int dwProcessId);

[STAThread]
static void Main()
{
    AttachConsole(-1);
    Console.WriteLine("Test1");
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new Form1());
    Console.WriteLine("WinForms exit");
}

但这里有一个问题:当打开表单并且用户关闭控制台时,我的程序会自动关闭。用户关闭控制台后,我需要让程序运行。我尝试SetConsoleCtrlHandler()在处理程序调用中使用和,FreeConsole()但在调用处理程序后程序仍然关闭:

static class Program
{
    [DllImport("Kernel32")]
    public static extern bool SetConsoleCtrlHandler(HandlerRoutine Handler, bool Add);

    // A delegate type to be used as the handler routine 
    // for SetConsoleCtrlHandler.
    public delegate bool HandlerRoutine(CtrlTypes CtrlType);

    private static bool ConsoleCtrlCheck(CtrlTypes ctrlType)
    {
        Console.OutputEncoding = Console.OutputEncoding;
        FreeConsole();
        return true;
    }

    [System.Runtime.InteropServices.DllImport("kernel32.dll")]
    private static extern bool AttachConsole(int dwProcessId);

    [System.Runtime.InteropServices.DllImport("kernel32.dll")]
    private static extern bool FreeConsole();

    [STAThread]
    static void Main()
    {
        AttachConsole(-1);
        SetConsoleCtrlHandler(ConsoleCtrlCheck, true);
        Console.WriteLine("Test1");
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
        Console.WriteLine("WinForms exit");
    }

    // An enumerated type for the control messages
    // sent to the handler routine.
    public enum CtrlTypes
    {
        CTRL_C_EVENT = 0,
        CTRL_BREAK_EVENT,
        CTRL_CLOSE_EVENT,
        CTRL_LOGOFF_EVENT = 5,
        CTRL_SHUTDOWN_EVENT
    }
}

用户关闭控制台时如何防止关闭 Windows 窗体应用程序?

4

1 回答 1

0

你可以像这样赶上窗口关闭事件

    private void winMain_Closing(object sender, CancelEventArgs e)
    {
        e.Cancel = true;
    }
于 2013-11-12T10:40:25.850 回答