你可以尝试这样的事情。
此代码将控制台窗口的位置设置为控制台应用程序。
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