tags:

views:

63

answers:

3

Hello everyone,

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.

A: 

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

You have to use combination of these -

http://stackoverflow.com/questions/2647820/toggle-process-startinfo-windowstyle-processwindowstyle-hidden-at-runtime/2648017#2648017

and

http://stackoverflow.com/questions/2636721/bring-another-processes-window-to-foreground-when-it-has-showintaskbar-false/2636915#2636915

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.

Nayan
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.
Lu Lu
You did not read my answer properly. Yes, `FindWindow` can do that.
Nayan
+1  A: 

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