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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With