Find and activate an application's window

前端 未结 3 1761
不知归路
不知归路 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 22:54

    You'd need to PInvoke the Windows API calls such as FindWindow and or EnumWindows and GetWindowText (for the title). Ideally you might also want to use GeWindowThreadProcessId so you can tie it down to the actual process.

    0 讨论(0)
  • 2021-02-12 23:04

    You have to use combination of these -

    Toggle Process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden at runtime

    and

    Bring another processes Window to foreground when it has ShowInTaskbar = false

    You need to find the class of the window and do a search on it. Read more about it here.

    Just for info, Notepad's class name is "Notepad" (without quotes). You can verify it using Spy++.

    Note: You cannot activate a window of an app if it was run with no window. Read more options in API here.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题