Blog Stats
  • Posts - 3
  • Articles - 0
  • Comments - 7
  • Trackbacks - 0

 

User32's SetForegroundWindow() API in C#

If there occurs a need to check if some process is already running and then bringing that process' main window in front then .NET does not helps 100%.

Using the System.Diagnositics.Process class to find out a already running process is a easy task but to bring that process' main window in front is a difficult goal.

Here's the code to get the already running process (e.g. Notepad) and then bringing it to front, using the native API from User32.dll >> SetForegroundWindow(int WindowHandle)

[System.Runtime.InteropServices.

class Program
{
static void Main(string[] args)
{
 System.Diagnostics.Process[] p = System.Diagnostics.Process.GetProcessesByName("notepad");
   if (p.Length > 0)
   {
     SetForegroundWindow(p[0].MainWindowHandle);
   }
 }
}

DllImport("user32.dll")]
public static extern bool SetForegroundWindow(IntPtr hWnd);

-Vaibhav Gaikwad


Feedback

# re: User32's SetForegroundWindow() API in C#

Gravatar This does not work if you calling form has TopMost set to true.......... 1/22/2008 4:47 AM | Someone

# re: User32's SetForegroundWindow() API in C#

Gravatar > This does not work if you calling form has TopMost set to true..........

Dumb comment, if TopMost no need to call SetForegroundWindow. 11/10/2008 12:23 PM | Zdis

# re: User32's SetForegroundWindow() API in C#

Gravatar can you tell me how to use [DllImport("user32.dll")] though i am using the namespace using System.Runtime.InteropServices its not wokring for me..
can u please help me.

Thanks in Advance. 11/13/2008 9:46 AM | dotnetdev

# re: User32's SetForegroundWindow() API in C#

Gravatar Sure I'll try my best, can you send your code snippet @ vaibhav.gaikwad[at]gmail[dot]com

Else you'll have to explain what is exactly not working for you. The System.Runtime.InteropServices is the correct namespace, but if something is not working I need to know what are you doing in the code and what kind of application is your's. 11/13/2008 11:21 AM | Vaibhav

# re: User32's SetForegroundWindow() API in C#

Gravatar Thanks man .it is working fine 4/30/2009 6:08 AM | kedar

# re: User32's SetForegroundWindow() API in C#

Gravatar Yes,
If you calling form has TopMost set to true,This does not work ! 7/8/2009 3:16 AM | dongyang

# re: User32's SetForegroundWindow() API in C#

Gravatar That works great !!! thanks.


[DllImport("user32.dll")]
public static extern bool
SetForegroundWindow(IntPtr hWnd);

calling in my Form1 as :

SetForegroundWindow(this.Handle); 11/12/2009 4:22 AM | titwan

Post a comment





 

 

 

Copyright © Vaibhav Gaikwad