C#获得windows任务栏窗口句柄及一些操作(放大、缩小、关闭、隐藏……)

需调用API函数

需在开头引入命名空间
using System.Runtime.InteropServices;

1、通过窗口名字查找

[DllImport("user32.dll", EntryPoint = "FindWindow")]
public static extern IntPtr FindWindow(string lp1, string lp2);

示例:

IntPtr hWnd = FindWindow(null, "abc");

2、对窗口进行在任务栏隐藏和打开操作

[DllImport("user32.dll", EntryPoint = "ShowWindow")]
public static extern IntPtr ShowWindow(IntPtr hWnd, int _value);

0    隐藏窗口到后台

1    正常大小显示窗口

3、获取当前焦点窗口的句柄

[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern IntPtr GetForegroundWindow();

使用方法 :   IntPtr myPtr=GetForegroundWindow();

4、获取到该窗口句柄后,可以对该窗口进行操作

[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern int ShowWindow(IntPtr hwnd, int nCmdShow);

使用实例:    ShowWindow(myPtr, 0);

0    关闭窗口

1    正常大小显示窗口

2    最小化窗口

3    最大化窗口

5、获取窗口大小,及屏幕坐标

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetWindowRect(IntPtr hWnd, ref RECT lpRect);

[StructLayout(LayoutKind.Sequential)]
        public struct RECT
        {
            public int Left;                             //最左坐标
            public int Top;                             //最上坐标
            public int Right;                           //最右坐标
            public int Bottom;                        //最下坐标
        }

示例:                 

                   InPtr awin = GetForegroundWindow();    //获取当前窗口

                   RECT rect = new RECT();
                   GetWindowRect(awin, ref rect);
                   int width = rect.Right - rect.Left;                        //窗口的宽度
                   int height = rect.Bottom - rect.Top;                   //窗口的高度

猜你喜欢

转载自blog.csdn.net/qq_40433102/article/details/84967483