C# native AppActivate method?
I want to activate an application (Excel) in code. If I reference
microsoft.visualbasic, I could use:
Interaction.AppActivate("Microsoft Excel");
But I wold rather use a native C# approach. I know that Interaction.MsgBox
has a native analog: MessageBox.Show.
Is there one for AppActivate?
Re: C# native AppActivate method?
I'm not sure but I think this will work:
Code:
System.Windows.Forms.Control.FromHandle(System.Diagnostics.Process.GetProcessesByName("Microsoft Excel")[0].MainWindowHandle).Focus();
Re: C# native AppActivate method?
OK, I tried that. I think we're really close but I got "Index was outside the bounds of the array." Clearly, the error is about the ("Microsoft Excel")[0].
Re: C# native AppActivate method?
try excel.exe
and you should modify the code to make sure the Process.GetProcessesByName returned something
Re: C# native AppActivate method?
The Process.MainWindowHandle property returns an IntPtr and the IntPtr type has no Focus method. You're trying to treat it like it returns a Form reference, which it couldn't because the window isn't a .NET Form anyway.
You do need to get the MainWindowHandle property value, but once you have it you have to go to the Windows API. SetForegroundWindow takes the handle of the window you want to activate. MainWindowHandle is that handle.
Re: C# native AppActivate method?
Thanks everyone. I'll stick to the VB reference.
Re: C# native AppActivate method?
Quote:
Originally Posted by CarlBuddig
Thanks everyone. I'll stick to the VB reference.
That's all well and good but if the app in question is minimised then AppActivate won't restore it anyway, so even in VB you have to use the Windows API if you want that functionality.
Re: C# native AppActivate method?
Quote:
The Process.MainWindowHandle property returns an IntPtr and the IntPtr type has no Focus method.
But the Control.FromHandle does
Re: C# native AppActivate method?
Quote:
Originally Posted by ComputerJy
But the Control.FromHandle does
Ah, didn't look closely enough did I? That said, a window in an unmanaged application is not a .NET control so you can't just create one from a handle. If the handle is not for a managed control to begin with then it's no help because Control.FromHandle will return null.