How to get process name and title of the top window on Windows / C#

前端 未结 4 553
故里飘歌
故里飘歌 2020-12-31 14:44

As in the topic... or better - how to get this information from events when the top window changes?

4条回答
  •  既然无缘
    2020-12-31 15:07

    You can find window handle by process name using this code:

     Process[] processes = Process.GetProcessesByName(m.ProcessName);
                                        if (processes != null && processes.Length > 0)
                                        {
                                            Process process = processes[0];
                                            process.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
                                            process.Refresh();
                                            if (process.MainWindowHandle != IntPtr.Zero)
                                            { // process.mainwindows handle is needed for you
    

    and than you can find window text by handle title = GetWindowTitle(process.MainWindowHandle);

    private String GetWindowTitle(IntPtr hWn)
            {
                object LParam = new object();
                int WParam = 0;
                StringBuilder title = new StringBuilder(1024);
                SendMessage(hWn, WM_GETTEXT, WParam, LParam);
                GetWindowText(hWn, title, title.Capacity);
                return title.ToString();
    
            }
    

    You need following declarations to call winapi functions:

     [DllImport("user32", CharSet = CharSet.Auto, SetLastError = true)]
            internal static extern int GetWindowText(IntPtr hWnd, [Out, MarshalAs(UnmanagedType.LPTStr)] StringBuilder lpString, int nMaxCount);
            [DllImport("User32.dll", EntryPoint = "SendMessage")]
            public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, object lParam);
    

提交回复
热议问题