关键词搜索

源码搜索 ×
×

c#对当前窗口进行关闭等操作

发布2021-04-12浏览2498次

详情内容

需调用API函数

需在开头引入命名空间

using System.Runtime.InteropServices;

获取当前窗口句柄:GetForegroundWindow()

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

返回值类型是IntPtr,即为当前获得焦点窗口的句柄

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

获取到该窗口句柄后,可以对该窗口进行操作.比如,关闭该窗口或在该窗口隐藏后,使其显示

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

nCmdShow的含义

0    关闭窗口

1    正常大小显示窗口

2    最小化窗口

3    最大化窗口

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


获取窗口大小及位置:需要调用方法GetWindowRect(IntPtr hWnd, ref RECT lpRect)

  1. [DllImport("user32.dll")]
  2. [return: MarshalAs(UnmanagedType.Bool)]
  3. static extern bool GetWindowRect(IntPtr hWnd, ref RECT lpRect);
  4. [StructLayout(LayoutKind.Sequential)]
  5. public struct RECT
  6. {
  7. public int Left; //最左坐标
  8. public int Top; //最上坐标
  9. public int Right; //最右坐标
  10. public int Bottom; //最下坐标
  11. }

示例:

  1. InPtr awin = GetForegroundWindow(); //获取当前窗口句柄
  2. RECT rect = new RECT();
  3. GetWindowRect(awin, ref rect);
  4. int width = rc.Right - rc.Left; //窗口的宽度
  5. int height = rc.Bottom - rc.Top; //窗口的高度
  6. int x = rc.Left;
  7. int y = rc.Top;

 

相关技术文章

最新源码

下载排行榜

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载