Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a running process the active Window

Tags:

c#

ms-access

Ok so I have three Microsoft Access databases. I want to be able to switch between these programmatically. I have a void method which accepts a string parameter called dbName (my database name).

public void SwitchDatabase(string dbName)
{

}

I know what the MainWindowTitle of my Access Database is and each database has a different MainWindowTitle so I can create an array of the Process class and make this equal so System.Diagnostics.Process.GetProcesses(). I can then loop through my running processes until I find the one where the ProcessName is MSACCESS and the MainWindowTitle is correct like so:

Process[] processList = Process.GetProcesses();

foreach (Process theProcess in processList)
{
    string processName = theProcess.ProcessName;
    string mainWindowTitle = theProcess.MainWindowTitle;
}

Once I find this, I can then grab the Process ID, and now I want to make this process my active window. How do I do this?

Thanks

like image 266
JMK Avatar asked Feb 16 '12 11:02

JMK


1 Answers

Eric's answer didn't work for me. I found a better solution here on SO with SetForegroundWindow. First I wondered, why it one time worked, next time it did'n.Then I excluded the current process from the list. So, here's my final version:

static void BringWindowToFront()
{
    var currentProcess = Process.GetCurrentProcess();
    var processes = Process.GetProcessesByName(currentProcess.ProcessName);
    var process = processes.FirstOrDefault(p => p.Id!=currentProcess.Id);
    if (process == null) return;

    SetForegroundWindow(process.MainWindowHandle);
}

[DllImport("user32.dll")]
static extern bool SetForegroundWindow(IntPtr hWnd);
like image 191
Slesa Avatar answered Sep 29 '22 12:09

Slesa