以下の動作をする Windows フォーム アプリケーションが必要です。
- プログラムがエクスプローラーから実行されている場合、コンソールなしで作業します (たとえば)。
- プログラムがコマンドラインから実行されているときからすべてのテキストをリダイレクトします
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");
}
しかし、ここで 1 つの問題があります。フォームを開いてユーザーがコンソールを閉じると、プログラムが自動的に閉じます。ユーザーがコンソールを閉じた後、プログラムを実行したままにする必要があります。ハンドラー呼び出しで andを使用しようと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 フォーム アプリケーションが閉じないようにするにはどうすればよいですか?