×

# C# 获取系统前景窗口(焦点窗口)

hqy hqy 发表于2026-04-08 16:56:32 浏览4 评论0

抢沙发发表评论

# C# 获取系统前景窗口(焦点窗口)

代码

C#
[DllImport("user32.dll")]static extern IntPtr GetForegroundWindow();[DllImport("user32.dll")]static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);[DllImport("user32.dll")]static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);[DllImport("psapi.dll")]static extern int GetProcessImageFileName(IntPtr hProcess, StringBuilder lpImageFileName, int nSize);const int nChars = 256;static StringBuilder buff = new StringBuilder(nChars);private ActiveInfo GetActiveWindow(){    IntPtr handle = GetForegroundWindow();    GetWindowThreadProcessId(handle, out uint id);    if (GetWindowText(handle, buff, nChars) > 0)    {        Process p = Process.GetProcessById((int)id);        string desc = string.Empty;        string filename = string.Empty;        try        {            ProcessModule main = p.MainModule;            if (main != null)            {                filename = main.FileName;                desc = main.FileVersionInfo.FileDescription;            }        }        catch (Exception)        {        }        return new ActiveInfo{         Title = buff.ToString(),          FileName = filename,         Desc= desc,         Pid  = id       };    }    return new ActiveInfo();}public sealed class ActiveInfo{    public string Title { get; set; } = string.Empty;    public string FileName { get; set; } = string.Empty;    public string Desc { get; set; } = string.Empty;    public uint Pid { get; set; }}


打赏

本文链接:https://kinber.cn/post/6408.html 转载需授权!

分享到:


推荐本站淘宝优惠价购买喜欢的宝贝:

image.png

 您阅读本篇文章共花了: 

群贤毕至

访客