设置位置WinForms应用程序
问题描述:
打开,我发现在这个线程一些源代码由雷克斯洛根张贴在这里的SO:设置位置WinForms应用程序
......还有还有一些非常有趣的代码发布在这个由Foredecker相同的线程,但它是不完整和复杂的:我没有足够的'追踪设施知道如何完全实现它...
我能够使用此控制台代码雷克斯(善意地)成功地发布在WinForms应用程序中以记录各种事件,并推送messa调试时使用的ges;我也可以从应用程序代码中清除它。
我似乎无法做的事情是当我打开控制台窗口(在主窗体加载事件中)时可靠地设置控制台窗口的屏幕位置。我得到的编译阻挡System.ArgumentOutOfRangeException错误,如果我尝试设置WindowLeft或WindowTop性质是这样的:
窗口的位置必须设置成 当前窗口大小的控制台的缓冲区内适合 和 号一定不能是负面的。 参数名:左实际值是 #
我可以,但是,设置WINDOWWIDTH和WINDOWHEIGHT性能。
我试图移动激活所述控制台的不同位置包括代码:
-
Program.cs文件之前的MainForm被的InitializeComponent“
- 之前和呼叫后运行”在
- ()中在MainForm的构造函数
- 在窗体的窗体Load事件
- 的Event
的孔索le在代码中的所有这些地方被激活了,但是在看起来随机切换左上象限中的那个地方看起来没有任何变化。
控制台窗口打开的位置随机变化(主窗体始终在屏幕上的相同位置初始化)。
答
你可以尝试这样的事情。
此代码将控制台窗口的位置设置为控制台应用程序。
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