设置在WinForms应用程序中打开的控制台窗口的位置

我在Rex Logan发布的这个post中发现了一些源代码:

链接文字

… Foredecker在同一个post中也发布了一些非常有趣的代码,但它不完整和复杂:我对’跟踪工具知道如何完全实现它不够了…

我能够在WinForms应用程序中成功发布此控制台代码Rex(友好地),以记录各种事件,并将消息推送到调试中非常有用; 我也可以从应用程序代码中清除它。

我似乎无法做的是在打开控制台窗口时(在主窗体加载事件中)可靠地设置控制台窗口的屏幕位置。 如果我尝试设置WindowLeft或WindowTop属性,我得到编译阻止System.ArgumentOutOfRangeException错误:

必须设置窗口位置,使当前窗口大小适合控制台的缓冲区,并且数字不能为负数。 参数名称:left实际值为#

但是,我可以设置WindowWidth和WindowHeight属性。

我试过移动激活控制台各个位置的代码,包括:

  1. 在MainForm运行之前的Program.cs文件中
  2. 在MainForm ctor中调用’InitializeComponent()之前和之后
  3. 在Form Load事件中
  4. 在Form Shown活动中

控制台在代码中的所有这些位置都可以正常激活,但看似随机切换屏幕左上象限的位置没有变化。

控制台窗口打开的位置似乎随机变化(主窗体始终在屏幕上的同一位置初始化)。

你可以尝试这样的事情。

此代码在控制台应用程序中设置控制台窗口的位置。

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()); } } }