专业网站建设品牌,十四年专业建站经验,服务6000+客户--广州京杭网络
免费热线:400-683-0016      微信咨询  |  联系我们

C#控制台应用程序如何将窗口移到屏幕中央

当前位置:网站建设 > 技术支持
资料来源:网络整理       时间:2023/2/14 1:13:54       共计:3604 浏览

制作了一个小的实用程序类,允许您将控制台窗口居中。

Usage example:


WindowUtility.MoveWindowToCenter();


完整源代码:


using System;

using System.Diagnostics;

using System.Runtime.InteropServices;


static class WindowUtility

{

   [DllImport("user32.dll", SetLastError = true)]

   static extern IntPtr FindWindow(string lpClassName, string lpWindowName);


   [DllImport("user32.dll", SetLastError = true)]

   static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);


   const uint SWP_NOSIZE = 0x0001;

   const uint SWP_NOZORDER = 0x0004;


   private static Size GetScreenSize() => new Size(GetSystemMetrics(0), GetSystemMetrics(1));


   private struct Size

   {

       public int Width { get; set; }

       public int Height { get; set; }


       public Size(int width, int height)

       {

           Width = width;

           Height = height;

       }

   }


   [DllImport("User32.dll", ExactSpelling = true, CharSet = CharSet.Auto)]

   private static extern int GetSystemMetrics(int nIndex);


   [DllImport("user32.dll")]

   [return: MarshalAs(UnmanagedType.Bool)]

   private static extern bool GetWindowRect(HandleRef hWnd, out Rect lpRect);


   [StructLayout(LayoutKind.Sequential)]

   private struct Rect

   {

       public int Left;        // x position of upper-left corner

       public int Top;         // y position of upper-left corner

       public int Right;       // x position of lower-right corner

       public int Bottom;      // y position of lower-right corner

   }


   private static Size GetWindowSize(IntPtr window)

   {

       if (!GetWindowRect(new HandleRef(null, window), out Rect rect))

           throw new Exception("Unable to get window rect!");


       int width = rect.Right - rect.Left;

       int height = rect.Bottom - rect.Top;


       return new Size(width, height);

   }


   public static void MoveWindowToCenter()

   {

       IntPtr window = Process.GetCurrentProcess().MainWindowHandle;


       if (window == IntPtr.Zero)

           throw new Exception("Couldn't find a window to center!");


       Size screenSize = GetScreenSize();

       Size windowSize = GetWindowSize(window);


       int x = (screenSize.Width - windowSize.Width) / 2;

       int y = (screenSize.Height - windowSize.Height) / 2;


       SetWindowPos(window, IntPtr.Zero, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER);

   }

}


版权说明:
本网站凡注明“广州京杭 原创”的皆为本站原创文章,如需转载请注明出处!
本网转载皆注明出处,遵循行业规范,如发现作品内容版权或其它问题的,请与我们联系处理!
欢迎扫描右侧微信二维码与我们联系。
·上一条:如何将C#控制台程序启动后隐藏? | ·下一条:c#获取CPU使用率高的进程

Copyright © 广州京杭网络科技有限公司 2005-2025 版权所有    粤ICP备16019765号 

广州京杭网络科技有限公司 版权所有