-1

In form1 I have a timer:

private void Form1_Load(object sender, EventArgs e)
        {
            System.Windows.Forms.Timer t1 = new System.Windows.Forms.Timer();
            t1.Interval = 50;
            t1.Tick += new EventHandler(timer1_Tick);
            t1.Enabled = true;
        }

The tick event:

private void timer1_Tick(object sender, EventArgs e)
        {
           label4.Text =  SetProcessWindow.ApplicationIsActivated().ToString();           

        }

And the ApplicationIsActivated method:

public static bool ApplicationIsActivated()
        {

            Process[] Processes = Process.GetProcesses();
            foreach (Process SingleProcess in Processes)
            {
                var activatedHandle = GetForegroundWindow();
                if (activatedHandle == IntPtr.Zero)
                {
                    return false;
                }
                var procId = SingleProcess.Id;//Process.GetCurrentProcess().Id;
                int activeProcId;
                GetWindowThreadProcessId(activatedHandle, out activeProcId);

                return activeProcId == procId;
            }            
        }

I want somehow to monitor the processes and if I move any process to the front then show me it in label4 in form1.

ApplicationIsActivated is not written good. First i'm not sure if making foreach each time is good and second i'm not sure how to return the activeProcId == procId; per process.

Manuel Spechia
  • 389
  • 1
  • 3
  • 16

1 Answers1

3

Instead of checking if each process is the activated one, you can find the activated process directly:

Process FindActivatedProcess()
{
    var activatedHandle = GetForegroundWindow();
    if (activatedHandle == IntPtr.Zero)
        return null;    // No window has focus

    int activeProcId;
    GetWindowThreadProcessId(activatedHandle, out activeProcId);
    return Process.GetProcessById(activeProcId);
}

[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
private static extern IntPtr GetForegroundWindow();

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern int GetWindowThreadProcessId(IntPtr handle, out int processId);

To determine when the activated application changes, you can do polling like you do now (though I suggest a larger interval -- 50ms seems like overkill to me), or you can ask Windows to notify you when it happens.

Community
  • 1
  • 1
Cameron
  • 96,106
  • 25
  • 196
  • 225
  • @Manuel: You're getting a null reference exception because you're unconditionally doing `FindActivatedProcess().Name`, but `FindActivatedProcess()` returns `null` when no activated process could be found. You need to put the result in a variable (e.g. `proc`) first, then do something like `Text = proc == null ? "" : proc.Name`. – Cameron Jul 08 '15 at 22:49