Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find and activate an application's window

Tags:

c#

.net

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 is undefined. So, I don't like to use to FindWindow which based on window's title.

My application is Winform C# 2.0. Thanks.

like image 845
Leo Vo Avatar asked May 12 '10 10:05

Leo Vo


1 Answers

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.

like image 87
Hans Passant Avatar answered Sep 26 '22 19:09

Hans Passant