I'm trying to set with c# a process window to the foreground / focus ( from a application that has no focus in that moment when doing it ), therefore i'm using the user32.dll static extern bool SetForegroundWindow(IntPtr hWnd)
method:
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);
public void setFocus()
{
SetForegroundWindow(process.MainWindowHandle);
}
every thing is working fine, but only if i have the visual studio 2008 open, i even dont need to to start the application from the VS08, its enough to have the project open with it. The moment i'm closing the project my application cant set the other window to the foreground. the only result is that in the taskbar the other window is blue highlighted. the moment i'm going to open my project with the VS08 again its working fine.
i have not the slightest idea why...i throught the problem could be that he cant import the dll but then it wouldnt be highligthed, and others win32 functions like static extern bool ShowWindow(IntPtr hWnd, IntPtr status);
are working even when the project is closed.
any solutions or hints for this problem ?
Edit:
i read the remarks for the function and i had the idea that my application has not the focus, so i tried this one:
[DllImport("user32.dll")]
static extern bool SetForegroundWindow(IntPtr hWnd);
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("user32.dll")]
static extern bool AllowSetForegroundWindow(int procID);
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", SetLastError = true)]
static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
public void setAUTFocus()
{
IntPtr hWnd = GetForegroundWindow();
uint processID = 0;
uint threadID = GetWindowThreadProcessId(hWnd, out processID);
int intID = (int)processID;
AllowSetForegroundWindow(intID);
SetForegroundWindow(process.MainWindowHandle);
}
now i'm searching for the window process that has focus at the moment and set the "AllowSetForegroundWindow" for this window and trying to set the focus on my window now. But the same problem, the moment i have the project in VS open its working, if not i getting only the blue highlight in the taskbar.
during i have my application running i can open / close the vs project, the moment its open everything is working, the moment its closed its not working, i have no interaction with the VS project while running my applicatiion. srsly i dont get it.
After searching a few days on the internet I have found one posible simple solution to make SetForegroundWindow to work on windows 7: press Alt key before calling SetForegroundWindow.
And the win32api imports
I had an issue with sending the Alt-key as it forced the window menu to open when I selected enter (instead of the OK button which is what I wanted).
This worked for me: