【问题标题】:Reposition console window relative to screen相对于屏幕重新定位控制台窗口
【发布时间】:2015-09-06 00:32:10
【问题描述】:

我正在开发一个 C# 控制台应用程序,我使用 Console.WindowHeight 增加了窗口的高度,但现在当应用程序第一次打开时,窗口的底部往往会离开屏幕。

有没有办法在控制台应用程序中设置控制台窗口相对于屏幕的位置?我查看了 Console.SetWindowPosition,但这只会影响控制台窗口相对于“屏幕缓冲区”的位置,这似乎不是我想要的。

感谢您的帮助!

【问题讨论】:

标签: c# console-application


【解决方案1】:

这里有一个解决方案,它使用窗口句柄和导入的SetWindowPos() 本机函数来实现您正在寻找的内容:

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


namespace ConsoleWindowPos
{
    static class Imports
    {
        public static IntPtr HWND_BOTTOM = (IntPtr)1;
       // public static IntPtr HWND_NOTOPMOST = (IntPtr)-2;
        public static IntPtr HWND_TOP = (IntPtr)0;
        // public static IntPtr HWND_TOPMOST = (IntPtr)-1;

        public static uint SWP_NOSIZE = 1;
        public static uint SWP_NOZORDER = 4;

        [DllImport("user32.dll", EntryPoint = "SetWindowPos")]
        public static extern IntPtr SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int x, int Y, int cx, int cy, uint wFlags);
    }

    class Program
    {

        static void Main(string[] args)
        {
            var consoleWnd = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle;
            Imports.SetWindowPos(consoleWnd, 0, 0, 0, 0, 0, Imports.SWP_NOSIZE | Imports.SWP_NOZORDER);
            System.Console.ReadLine();
        }
    }
}

代码将控制台窗口移动到屏幕的左上角,既不改变 z 顺序也不改变窗口的宽度/高度。

【讨论】:

  • 非常感谢您的回复!出于某种原因,这对我还不起作用;即窗口仍在屏幕的中间区域打开。
  • 是的,但它应该“跳”到左上角。这就是它对我的作用。你是不是在 SetWindowPos() 之前设置了一个断点?
  • 我就是这样做的。在带有 VS2015 社区版的 Windows 7 x64 上,调试|任何 CPU 构建配置。
  • 所以我尝试用断点运行它,并且肯定看到它跳到了左上角。是否有可能让它保持在那个位置?
  • 在不使用调试的情况下无法使其在运行 Windows 10 x64 和 Visual Studio 2015 的系统上运行。不过,感谢您的努力。
【解决方案2】:

您可以使用Console.SetWindowPosition(int left, int top),它适用于 .NET Framework 和 .NET 5.0。

【讨论】:

  • 这设置了错误的“位置”而不是所要求的 - 请参阅原始问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-06
  • 2010-11-01
  • 2022-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-08
相关资源
最近更新 更多