18

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.

Leo Vo
  • 9,980
  • 9
  • 56
  • 78

3 Answers3

33

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.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • Wow It's what I'm looking for too! but if window state is minimized it doesn't work! how to solve it? – ACE Apr 09 '15 at 10:46
  • Hmya, putting a minimized window in the foreground is not a good idea. Click the Ask Question button. – Hans Passant Apr 09 '15 at 10:51
  • why!? Could you please give the solution? – ACE Apr 09 '15 at 13:30
  • Process by TITLE name how do you tell? (such as Google Chrome is the process but it has many TITLE names) –  Sep 24 '16 at 09:16
0

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.

Lloyd
  • 29,197
  • 4
  • 84
  • 98
  • Note: the window title is undefined. So, I don't like to use to FindWindow which based on window's title. – Leo Vo May 12 '10 at 10:06
  • FindWindow is hit or miss. Use EnumWindows along with the process specific stuff then. You might also want to make sure you find the main window of the application and not a sub-window, check the styles for that. – Lloyd May 12 '10 at 10:10
0

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.

Community
  • 1
  • 1
Nayan
  • 3,092
  • 25
  • 34
  • Thank a lot, but I wonder that FindWindow can help me to find an application's window (window handle) when it's title is undefined. Thanks. – Leo Vo May 12 '10 at 11:09
  • You did not read my answer properly. Yes, `FindWindow` can do that. – Nayan May 13 '10 at 11:29