我在 Rex Logan 在 SO 上发布的这个线程中找到了一些源代码:
... Foredecker 在同一个线程中也发布了一些非常有趣的代码,但它不完整且复杂:我对“跟踪工具”的了解还不够多,不知道如何完全实现它.. .
我能够使用 Rex(友善地)在 WinForms 应用程序中成功发布的此控制台代码来记录各种事件,并推送对调试有用的消息;我也可以从应用程序代码中清除它。
我似乎无法做的是在打开控制台窗口时可靠地设置控制台窗口的屏幕位置(在主窗体加载事件中)。如果我尝试像这样设置 WindowLeft 或 WindowTop 属性,我会遇到编译阻塞 System.ArgumentOutOfRangeException 错误:
The window position must be set such that the current window size fits within the console's buffer, and the numbers must not be negative. Parameter name: left Actual value was #
但是,我能够设置 WindowWidth 和 WindowHeight 属性。
我已经尝试将激活控制台的代码移动到各个位置,包括:
- 在“运行 MainForm”之前的 Program.cs 文件中
- 在调用 MainForm 构造器中的“InitializeComponent()”之前和之后
- 在表单加载事件中
- 在 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, IntPtr 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, IntPtr 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());
}
}
}
关于c# - 设置在 WinForms 应用程序中打开的控制台窗口的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1548838/