[DllImport("user32.dll")]
static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
[DllImport("kernel32.dll", ExactSpelling = true)]
static extern IntPtr GetConsoleWindow();
const int SW_RESTORE = 9; // Restore window if minimized or not in normal state
const int SW_MAXIMIZE = 3; // Command to maximize the window
class Program
{
static void Main(string[] args)
{
ConsoleManipulator consoleManipulator = new ConsoleManipulator();
// Bring the console window to the front
consoleManipulator.BringConsoleToFront();
// Maximize the console window
consoleManipulator.MaximizeConsole();
Console.ReadLine(); // Keep the console open to observe changes
}
}
// Method to bring the console window to the front
public void BringConsoleToFront()
{
IntPtr consoleWindow = GetConsoleWindow();
if (consoleWindow != IntPtr.Zero)
{
// First, restore the window if it’s minimized or not normal
ShowWindow(consoleWindow, SW_RESTORE);
Console.WriteLine("Console restored.");
// Bring to front
SetForegroundWindow(consoleWindow);
Console.WriteLine("Console brought to the front.");
}
}
// Method to maximize the console window
public void MaximizeConsole()
{
IntPtr consoleWindow = GetConsoleWindow();
if (consoleWindow != IntPtr.Zero)
{
ShowWindow(consoleWindow, SW_MAXIMIZE); // Maximize the window
Console.WriteLine("Console maximized.");
}
else
{
Console.WriteLine("Failed to get console window handle.");
}
}
我只是使用 extern SetForegroundWindow、ShowWindow 和 GetConsoleWindow 创建控制台应用程序。
当我使用所示代码运行程序时,
consoleManipulator.BringConsoleToFront()
将控制台带到 Visual Studio 的前面,但MaximizeConsole()
无法最大化控制台。控制台应用程序保持实际尺寸高度和宽度不变...
尝试使用我的 NuGet 包 ConsoleHelperLibrary,它面向 NET6 及更高版本。
以下最大化控制台窗口。
WindowUtility.SetConsoleWindowPosition(WindowUtility.AnchorWindow.Fill);
以下GitHub存储库中有几个代码示例。