基于C#实现获取Windows所有窗口句柄

 更新时间:2023年12月17日 08:09:19   作者:rjcql  
在做录屏或截屏操作时,需要获取当前正在运行中的桌面程序句柄,所以这篇文章主要为大家详细介绍了如何使用C#实现获取Windows所有窗口句柄,需要的可以参考下

写在前面

在做录屏或截屏操作时,需要获取当前正在运行中的桌面程序句柄,在网上查找资源的的时候,发现了一个工具类还不错,这边做个验证记录。

参考代码

    public class WindowApi
    {
        //寻找目标进程窗口       
        [DllImport("USER32.DLL")]
        public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
        //设置进程窗口到最前       
        [DllImport("USER32.DLL")]
        public static extern bool SetForegroundWindow(IntPtr hWnd);
 
        #region GetWindowCapture的dll引用
        [DllImport("user32.dll")]
        private static extern IntPtr GetWindowRect(IntPtr hWnd, ref Rectangle rect);
 
        [DllImport("gdi32.dll")]
        private static extern IntPtr CreateCompatibleDC(
         IntPtr hdc // handle to DC
         );
        [DllImport("gdi32.dll")]
        private static extern IntPtr CreateCompatibleBitmap(
         IntPtr hdc,         // handle to DC
         int nWidth,      // width of bitmap, in pixels
         int nHeight      // height of bitmap, in pixels
         );
        [DllImport("gdi32.dll")]
        private static extern IntPtr SelectObject(
         IntPtr hdc,           // handle to DC
         IntPtr hgdiobj    // handle to object
         );
        [DllImport("gdi32.dll")]
        private static extern int DeleteDC(
         IntPtr hdc           // handle to DC
         );
        [DllImport("user32.dll")]
        private static extern bool PrintWindow(
         IntPtr hwnd,                // Window to copy,Handle to the window that will be copied.
         IntPtr hdcBlt,              // HDC to print into,Handle to the device context.
         UInt32 nFlags               // Optional flags,Specifies the drawing options. It can be one of the following values.
         );
        [DllImport("user32.dll")]
        private static extern IntPtr GetWindowDC(
         IntPtr hwnd
         );
        #endregion
        /// <summary>
        /// 根据句柄获取截图
        /// </summary>
        /// <param name="hWnd"></param>
        /// <returns></returns>
        public static Bitmap GetWindowCapture(IntPtr hWnd)
        {
            IntPtr hscrdc = GetWindowDC(hWnd);
            Rectangle windowRect = new Rectangle();
            GetWindowRect(hWnd, ref windowRect);
            int width = Math.Abs(windowRect.X - windowRect.Width);
            int height = Math.Abs(windowRect.Y - windowRect.Height);
            IntPtr hbitmap = CreateCompatibleBitmap(hscrdc, width, height);
            IntPtr hmemdc = CreateCompatibleDC(hscrdc);
            SelectObject(hmemdc, hbitmap);
            PrintWindow(hWnd, hmemdc, 0);
            Bitmap bmp = Image.FromHbitmap(hbitmap);
            DeleteDC(hscrdc);//删除用过的对象
            DeleteDC(hmemdc);//删除用过的对象
            return bmp;
        }
        /// <summary>
        /// 根据句柄获取截图路径
        /// </summary>
        /// <param name="hWnd"></param>
        /// <returns></returns>
        public static string GetCapturePath(IntPtr hWnd)
        {
            string path = string.Empty;
            string dicPath = AppDomain.CurrentDomain.BaseDirectory + "Intercept";
            if (!Directory.Exists(dicPath))
            {
                Directory.CreateDirectory(dicPath);
            }
            using (Bitmap bitmap = GetWindowCapture(hWnd))
            {
                path = dicPath + "\\" + Guid.NewGuid().ToString().Replace("-", "") + ".png";
                bitmap.Save(path);
            }
            return path;
        }
 
 
        private delegate bool WNDENUMPROC(IntPtr hWnd, int lParam);
 
        //用来遍历所有窗口 
        [DllImport("user32.dll")]
        private static extern bool EnumWindows(WNDENUMPROC lpEnumFunc, int lParam);
 
        //获取窗口Text 
        [DllImport("user32.dll")]
        private static extern int GetWindowTextW(IntPtr hWnd, [MarshalAs(UnmanagedType.LPWStr)] StringBuilder lpString, int nMaxCount);
 
        //获取窗口类名 
        [DllImport("user32.dll")]
        private static extern int GetClassNameW(IntPtr hWnd, [MarshalAs(UnmanagedType.LPWStr)] StringBuilder lpString, int nMaxCount);
 
        //自定义一个结构,用来保存句柄信息
        public struct WindowInfo
        {
            public IntPtr hWnd;
            public string szWindowName;
            public string szClassName;
        }
 
        public static WindowInfo[] GetAllDesktopWindows()
        {
            //用来保存窗口对象 列表
            List<WindowInfo> wndList = new List<WindowInfo>();
 
            //enum all desktop windows 
            EnumWindows(delegate (IntPtr hWnd, int lParam)
            {
                WindowInfo wnd = new WindowInfo();
                StringBuilder sb = new StringBuilder(256);
 
                //get hwnd 
                wnd.hWnd = hWnd;
 
                //get window name  
                GetWindowTextW(hWnd, sb, sb.Capacity);
                wnd.szWindowName = sb.ToString();
 
                //get window class 
                GetClassNameW(hWnd, sb, sb.Capacity);
                wnd.szClassName = sb.ToString();
 
                //add it into list 
                wndList.Add(wnd);
                return true;
            }, 0);
 
            return wndList.ToArray();
        }
 
        [DllImport("kernel32.dll", EntryPoint = "SetProcessWorkingSetSize")]
        public static extern int SetProcessWorkingSetSize(IntPtr process, int minSize, int maxSize);
 
        /// <summary>
        /// 释放内存
        /// </summary>
        public async static Task ClearMemory()
        {
            //获得当前工作进程
            Process proc = Process.GetCurrentProcess();
            long usedMemory = proc.PrivateMemorySize64;
            if (usedMemory > 1024 * 1024 * 10)
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();
                if (Environment.OSVersion.Platform == PlatformID.Win32NT)
                {
                    SetProcessWorkingSetSize(Process.GetCurrentProcess().Handle, -1, -1);
                }
                await Task.Delay(10);
            }
        }
    }

调用结果

调用示意:

var programList = WindowApi.GetAllDesktopWindows().Where(x => !string.IsNullOrEmpty(x.szWindowName)).ToList();
listBoxWindows.DataSource = programList.Select(x => x.szWindowName).ToList(); 

以上就是基于C#实现获取Windows所有窗口句柄的详细内容,更多关于C#获取Windows窗口句柄的资料请关注脚本之家其它相关文章!

相关文章

  • C#读取命令行参数的方法

    C#读取命令行参数的方法

    这篇文章主要介绍了C#读取命令行参数的方法,可实现读取程序输入命令行的所有参数,便于调试程序,比较简单实用,需要的朋友可以参考下
    2015-04-04
  • C#和SQL实现的字符串相似度计算代码分享

    C#和SQL实现的字符串相似度计算代码分享

    这篇文章主要介绍了C#和SQL实现的字符串相似度计算代码分享,本文分别给出了C#语言和SQL语言的实现代码,需要的朋友可以参考下
    2014-10-10
  • C# ThreadPool之QueueUserWorkItem使用案例详解

    C# ThreadPool之QueueUserWorkItem使用案例详解

    这篇文章主要介绍了C# ThreadPool之QueueUserWorkItem使用案例详解,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下
    2021-08-08
  • C#中DateTime日期类型格式化显示方法汇总

    C#中DateTime日期类型格式化显示方法汇总

    这篇文章主要介绍了C#中DateTime日期类型格式化显示方法汇总
    2014-07-07
  • C#使用NPOI对word进行读写

    C#使用NPOI对word进行读写

    这篇文章介绍了C#使用NPOI对word进行读写的方法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-06-06
  • C#之App.Config文件操作的实现

    C#之App.Config文件操作的实现

    AppConfigHelper提供了一种方便的方式来读取、添加、修改和删除应用程序配置文件中的配置项,本文主要介绍了C#之App.Config文件操作的实现,感兴趣的可以了解一下
    2026-01-01
  • DirectoryInfo引用一个相对目录的实例

    DirectoryInfo引用一个相对目录的实例

    这种特殊参数在Windows的命令提示符或者“运行”对话框中都可以使用,等价于DOS中的cd命令参数。直接上代码,一看你就懂了:
    2013-04-04
  • c#给图片添加文字的代码小结

    c#给图片添加文字的代码小结

    c#编程中,我们需要为图片添加文字水印,那么就可以参考下面的几个代码
    2012-11-11
  • C#拷贝整个文件夹及子目录和其中文件的方法

    C#拷贝整个文件夹及子目录和其中文件的方法

    这篇文章主要介绍了C#拷贝整个文件夹以及子目录和其中文件,本文通过实例代码给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
    2019-06-06
  • C#之System.Threading.Lock与lock使用及区别

    C#之System.Threading.Lock与lock使用及区别

    本文详细比较了C#中传统lock语句与System.Threading.Lock的异同,涵盖语法复杂度、异常处理、超时控制及性能影响等方面,帮助开发者选择合适的同步机制
    2026-05-05

最新评论