您可以使用System.Console 类的Console.WindowTop 和Console.WindowWidth 来设置控制台窗口的位置。
Here 是 MSDN 上的示例
BufferHeight 和 BufferWidth 属性获取/设置要显示的行数和列数。
WindowHeight 和 WindowWidth 属性必须始终分别小于 BufferHeight 和 BufferWidth。
WindowLeft 必须小于BufferWidth - WindowWidth 并且WindowTop 必须小于BufferHeight - WindowHeight。
WindowLeft 和 WindowTop 是相对于缓冲区的。
要移动实际的控制台窗口,this 文章有一个很好的例子。
我使用了您的一些代码和 CodeProject 示例中的代码。您可以在一个函数中设置窗口位置和大小。无需再次设置Console.WindowHeight 和Console.WindowWidth。这就是我的班级的样子:
class Program
{
const int SWP_NOZORDER = 0x4;
const int SWP_NOACTIVATE = 0x10;
[DllImport("kernel32")]
static extern IntPtr GetConsoleWindow();
[DllImport("user32")]
static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter,
int x, int y, int cx, int cy, int flags);
static void Main(string[] args)
{
Console.WindowWidth = 50;
Console.WindowHeight = 3;
Console.BufferWidth = 50;
Console.BufferHeight = 3;
Console.BackgroundColor = ConsoleColor.Black;
Console.ForegroundColor = ConsoleColor.DarkMagenta;
var screen = System.Windows.Forms.Screen.PrimaryScreen.Bounds;
var width = screen.Width;
var height = screen.Height;
SetWindowPosition(100, height - 300, 500, 100);
Console.Title = "My Title";
Console.WriteLine("");
Console.Write(" Press any key to close this window ...");
Console.ReadKey();
}
/// <summary>
/// Sets the console window location and size in pixels
/// </summary>
public static void SetWindowPosition(int x, int y, int width, int height)
{
SetWindowPos(Handle, IntPtr.Zero, x, y, width, height, SWP_NOZORDER | SWP_NOACTIVATE);
}
public static IntPtr Handle
{
get
{
//Initialize();
return GetConsoleWindow();
}
}
}