一、根据Win32 API定义窗口相关函数:
/// <summary> /// 查找窗口句柄 /// </summary> /// <param name="lpClassName">类名</param> /// <param name="lpWindowName">窗口名</param> /// <returns>返回查找到的窗口句柄</returns> [DllImport("user32.dll")] public static extern IntPtr FindWindow(string lpClassName, string lpWindowName); /// <summary> /// 显示或隐藏窗口 /// </summary> /// <param name="hWnd">窗口句柄</param> /// <param name="nCmdShow">0为隐藏,1为显示</param> /// <returns>返回显示或隐藏是否成功</returns> [DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
二、设置控制台窗口的显示或隐藏:
/// <summary> /// 设置控制台窗口是否显示 /// </summary> /// <param name="visible">是否显示</param> public static void SetConsoleWindowVisible(bool visible) { // 查找控制台窗口句柄 IntPtr hWnd = FindWindow(null, Console.Title); // 判断是否找到控制台窗口句柄 if (hWnd != IntPtr.Zero) { // 设置控制台窗口显示或隐藏 if (visible) { ShowWindow(hWnd, 1); } else { ShowWindow(hWnd, 0); } } }