Find and activate an application's window

前端 未结 3 1771
不知归路
不知归路 2021-02-12 22:41

Assume that notepad.exe is opening and the it\'s window is inactive. I will write an application to activate it. How to make?

Update: The window title i

3条回答
  •  囚心锁ツ
    2021-02-12 23:12

    You'll need to P/invoke SetForegroundWindow(). Process.MainWindowHandle can give you the handle you'll need. For example:

    using System;
    using System.Diagnostics;
    using System.Runtime.InteropServices;
    
    class Program {
        static void Main(string[] args) {
            var prc = Process.GetProcessesByName("notepad");
            if (prc.Length > 0) {
                SetForegroundWindow(prc[0].MainWindowHandle);
            }
        }
        [DllImport("user32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);
    }
    

    Note the ambiguity if you've got more than one copy of Notepad running.

提交回复
热议问题