# 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; }
}