2

一些研究告诉我,.NET 控制台应用程序 API 本身并不支持将控制台窗口本身的位置设置在您桌面上的任何 X/Y 位置。这令人沮丧,因为我有两个监视器,一个是我的主要代码监视器,另一个是我显示 UI(ASP.NET 网页、控制台应用程序、WinForms 窗口等)的地方。当我执行我的控制台应用程序时,它想在 Visual Studio 后面打开,但我希望它在我的另一个监视器上打开。

我是否需要调用 Win32 API 才能执行此操作?还有其他方法吗?

更新: kingalligator 的解决方案在MoveWindow()API 调用中使用任意硬编码值时完美运行。但是,当应用从 GetWindowRect() API 调用中获取的 RECT 尺寸时,您需要通过减去.topfrom来设置高度,.bottom如下所示。如果你只是传入.bottom,窗口会逐渐增加高度。奇怪的是,你不必做这个数学运算,.left.right就是让我如此困惑的原因。

RECT rect = new RECT();
IntPtr ptr = GetConsoleWindow();

for (int i = 0; i < 5; i++)
{
    GetWindowRect(ptr, ref rect);
    MoveWindow(ptr, rect.left, rect.top, rect.right, rect.bottom - rect.top, true);
}
4

1 回答 1

3

是的,看起来有一种方法——至少在 C# 中。您指定了 .NET,所以我也尝试在 VB 中执行此操作,但无法使其工作。以下代码中最重要的部分是MoveWindow(IntPtr hwnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);

参数有:句柄、窗口 x 位置、窗口 y 位置、窗口宽度、窗口高度和一个布尔值,表示是否要重新绘制窗口。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

public struct RECT
{
    public int left;
    public int top;
    public int right;
    public int bottom;
}

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            Console.Title = "Test";
            IntPtr handle = FindWindowByCaption(IntPtr.Zero, Console.Title);
            MoveWindow(handle, 100, 300, 200, 200, true);
            Console.WriteLine("Hi");

            RECT thisRect = new RECT();
            GetWindowRect(handle, ref thisRect);
            Console.WriteLine(thisRect.left);
            Console.WriteLine(thisRect.top);
            Console.ReadKey();
            return;

        }

        [DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
        public static extern IntPtr FindWindowByCaption(IntPtr zeroOnly, string lpWindowName);

        [DllImport("user32.dll", SetLastError = true)]
        internal static extern bool MoveWindow(IntPtr hwnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);

        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention =      CallingConvention.StdCall, ExactSpelling = true, SetLastError = true)]
        public static extern bool GetWindowRect(IntPtr hWnd, ref RECT rect);

    }
}
于 2013-06-27T12:21:24.713 回答