Search code examples
c#ms-access

Make a running process the active Window


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?


Solution

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