Wednesday, June 18, 2014

SetForegroundWindow Win32 API not always works on Windows 7

SetForegroundWindows has some remarks usage, which could be found here:

At least one of the following must be 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.
  • The foreground lock time-out has expired (see SPI_GETFOREGROUNDLOCKTIMEOUT in SystemParametersInfo).
  • No menus are active.
Alternative solution is to use  AttachedThreadInputAction pattern:

Other "classic" approaches using Mutexes and EventWaitHandle:

VB style approach:

using System;
using System.Windows.Forms;
using Microsoft.VisualBasic.ApplicationServices;    // Add reference to Microsoft.VisualBasic

namespace WindowsFormsApplication1 {
    class Program : WindowsFormsApplicationBase {
        public Program() {
            this.EnableVisualStyles = true;
            this.IsSingleInstance = true;
            this.MainForm = new Form1();
        protected override void OnStartupNextInstance(StartupNextInstanceEventArgs e) {
            e.BringToForeground = true;
        public static void Main(string[] args) {
            new Program().Run(args);

Powered by Blogger.