你可以嘗試這樣的事情。
此代碼將控制檯窗口的位置設置爲控制檯應用程序。
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace ConsoleApplication10
{
class Program
{
const int SWP_NOSIZE = 0x0001;
[DllImport("kernel32.dll", ExactSpelling = true)]
private static extern IntPtr GetConsoleWindow();
private static IntPtr MyConsole = GetConsoleWindow();
[DllImport("user32.dll", EntryPoint = "SetWindowPos")]
public static extern IntPtr SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int x, int Y, int cx, int cy, int wFlags);
static void Main(string[] args)
{
int xpos = 300;
int ypos = 300;
SetWindowPos(MyConsole, 0, xpos, ypos, 0, 0, SWP_NOSIZE);
Console.WriteLine("any text");
Console.Read();
}
}
}
此代碼設置在WinForm應用程序控制檯窗口的位置。
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace WindowsFormsApplication10
{
static class Program
{
const int SWP_NOSIZE = 0x0001;
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
private static extern bool AllocConsole();
[DllImport("user32.dll", EntryPoint = "SetWindowPos")]
public static extern IntPtr SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int x, int Y, int cx, int cy, int wFlags);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr GetConsoleWindow();
[STAThread]
static void Main()
{
AllocConsole();
IntPtr MyConsole = GetConsoleWindow();
int xpos = 1024;
int ypos = 0;
SetWindowPos(MyConsole, 0, xpos, ypos, 0, 0, SWP_NOSIZE);
Console.WindowLeft=0;
Console.WriteLine("text in my console");
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
謝謝RRUZ;我能夠將您的代碼合併到Rex Logan發佈的基本代碼中,並將控制檯窗口設置爲我想要的地方。 我只是好奇:爲什麼要調用'Console.Read()?這是一個我正在運行的WinForms應用程序,並且我僅將控制檯用於「日誌記錄」:在WinForm應用程序中初始化控制檯時,這是一個標準的事情嗎? 非常感謝!最好,賬單 – BillW 2009-10-10 20:15:02
@BillW - 它在那裏,讓窗口保持可見狀態,直到你點擊'return'。該示例在設置窗口位置後不做任何操作,因此只會關閉,您不會看到它具有正確的位置。 – ChrisF 2009-10-10 20:22:42
嗨ChrisF, 感謝您的迴應! fyi:使用我在原始請求中鏈接的Rex Logan發佈的代碼,控制檯窗口確實存在,不需要任何對Console.Read()的調用。 best,Bill – BillW 2009-10-11 03:49:46