tags:

views:

34

answers:

3

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?

A: 

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.

Oded
The problem I'm facing is, how do I make that process window the active window.
manyxcxi
A: 

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.

Gmoliv
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)
manyxcxi
+2  A: 

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.
driis
Thank you very much for a VERY detailed answer. I will try implementing this immediately.
manyxcxi
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
manyxcxi