As part of an application, I’ve added a shortcut bar for relevantly used programs. I have it set up to check if the application is open already, and if it is to switch to it instead of opening another instance. This works fine for programs like calc and notepad, but all the MS Office programs open another instance no matter what, and I’d like them not to.
Office Button
private void wordButton_Click(object sender, RoutedEventArgs e)
{
try
{
SwitchToProcess("winword.exe", "C:\\Program Files (x86)\\Microsoft Office\\Office14\\winword.exe");
}
catch (Win32Exception)
{
try
{
SwitchToProcess("winword.exe", "C:\\Program Files\\Microsoft Office\\Office14\\winword.exe");
}
catch (Win32Exception)
{
}
}
}
Notepad Button
private void notepadLink_Click(object sender, RoutedEventArgs e)
{
SwitchToProcess("notepad.exe");
}
Methods
private void SwitchToProcess(string name)
{
Process[] procs = Process.GetProcesses();
if (procs.Length != 0)
{
for (int i = 0; i < procs.Length; i++)
{
try
{
if (procs[i].MainModule.ModuleName == name)
{
IntPtr hwnd = procs[i].MainWindowHandle;
ShowWindowAsync(hwnd, SW_RESTORE);
SetForegroundWindow(hwnd);
return;
}
}
catch
{
}
}
}
else
{
MessageBox.Show("No process running");
return;
}
launchApp.StartInfo.FileName = name;
launchApp.Start();
}
private void SwitchToProcess(string name, string path)
{
Process[] procs = Process.GetProcesses();
if (procs.Length != 0)
{
for (int i = 0; i < procs.Length; i++)
{
try
{
if (procs[i].MainModule.ModuleName == name)
{
IntPtr hwnd = procs[i].MainWindowHandle;
ShowWindowAsync(hwnd, SW_RESTORE);
SetForegroundWindow(hwnd);
return;
}
}
catch
{
}
}
}
else
{
MessageBox.Show("No process running");
return;
}
launchApp.StartInfo.FileName = path;
launchApp.Start();
}
The reason for the two different directories in the Office button is a simple way of ensuring that x86/x64 install locations don’t cause a problem. The computers I’m developing this for have the registry locked out, so I can’t check which one is correct.
Ok, so after digging a little deeper into Google, I finally figured out the problem. I had the program targeted for an x86 processor, and am running it on x64. Switched the target to AnyCPU and it works perfectly. Apparently it was catching an error of
Only part of a ReadProcessMemory or WriteProcessMemory request was completed, but since I had the try-catch block in there it wasn’t displaying the error until I used StepInto repeatedly on the 77-item processor array. Thanks everyone for the help though.