I'm trying to create a basic macro recording/playback system. If I wanted to select an open application (like notepad) to bring it to the front for input, how would I go about calling it by name or some other referanceable attribute?
3 Answers
Here is an example. Basically, get the Process, then call SetForegroundWindow on it's MainWindowHandle:
using System;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
namespace StackOverflow.Test
{
class Program
{
static void Main(string[] args)
{
var proc = Process.GetProcessesByName("notepad").FirstOrDefault();
if (proc != null && proc.MainWindowHandle != IntPtr.Zero)
SetForegroundWindow(proc.MainWindowHandle);
}
[DllImport("user32")]
private static extern bool SetForegroundWindow(IntPtr hwnd);
}
}
You should be aware of the restrictions:
The system restricts which processes can set the foreground window. A process can set the foreground window only if one of the following conditions is true:
- The process is the foreground process.
- The process was started by the foreground process.
- The process received the last input event.
- There is no foreground process.
- The foreground process is being debugged.
- The foreground is not locked (see LockSetForegroundWindow).
- The foreground lock time-out has expired (see SPI_GETFOREGROUNDLOCKTIMEOUT in SystemParametersInfo).
- No menus are active.

- 161,458
- 45
- 265
- 341
-
Thank you very much for a VERY detailed answer. I will try implementing this immediately. – ashurexm Oct 19 '10 at 19:40
-
This seems to work, but I'm having a peculiar issue. I've asked it as a new question here: http://stackoverflow.com/questions/3973532 – ashurexm Oct 19 '10 at 23:13
You can start by using Process.GetProcesses
- this will give you a list of all running processes. Examine the different properties on each process - this should get you going.

- 489,969
- 99
- 883
- 1,009
-
The problem I'm facing is, how do I make that process window the active window. – ashurexm Oct 19 '10 at 19:00
Checkout an app named "Autohotkey", it does everything you need and saves you a lot of programming time, and it's free.
If autohotkey doesn't solve your problems or if you're doing this for learning purposes, someone asked a "brand-new" app, etc., there are some links that may be helpful:
Bringing Window to the Front in C# using Win32 API http://social.msdn.microsoft.com/Forums/en-US/vssmartdevicesvbcs/thread/92823775-29f6-4950-bf06-d2f1ca89ec8d (it says "mobile windows" but still can be helpful)
Hope it helps.

- 1
- 1

- 1,595
- 11
- 17
-
I've actually looked at autohotkey. It is definitely a useful looking app, the problem is that this has to be an in-house type of thing due to 3rd party restrictions and future intended use (macro input based off picklists,etc) – ashurexm Oct 19 '10 at 18:59