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?
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.
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:
http://stackoverflow.com/questions/2987/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.
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.