简体   繁体   中英

Make a running process the active Window

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

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);

Try this:

[DllImport("user32.dll", CharSet=CharSet.Auto,ExactSpelling=true)]
public static extern IntPtr SetFocus(HandleRef hWnd);


[TestMethod]
public void PlayAround()
{
    Process[] processList = Process.GetProcesses();

    foreach (Process theProcess in processList)
    {
        string processName = theProcess.ProcessName;
        string mainWindowTitle = theProcess.MainWindowTitle;
        SetFocus(new HandleRef(null, theProcess.MainWindowHandle));
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM