Today I had the problem that I want to start outlook minimized and automatically in C#. First I tried to use ProcessWindowStyle.Minimized as in this snippet:
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.WindowStyle = ProcessWindowStyle.Minimized;
// ...
Process.Start(startInfo)
But this approach won’t work with Outlook. I tried a few other methods but I couldn’t get it to work so I posted my question at stackoverflow. After this I went lucky and found out that the MainWindowHandle changes if Outlook was loaded. I build a loop and wrote the output of the MainWindowTitle into the console. The output was this:
At this point I started to develop a solution and came up with this:
[DllImport("user32.dll")]
private static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
// console application entry point
static void Main()
{
// check if process already runs, otherwise start it
if(Process.GetProcessesByName("OUTLOOK").Count().Equals(0))
Process.Start("OUTLOOK");
// get running process
var process = Process.GetProcessesByName("OUTLOOK").First();
// as long as the process is active
while (!process.HasExited)
{
// title equals string.Empty as long as outlook is minimized
// title starts with "öffnen" (engl: opening) as long as the programm is loading
string title = Process.GetProcessById(process.Id).MainWindowTitle;
// "posteingang" is german for inbox
if (title.ToLower().StartsWith("posteingang"))
{
// minimize outlook and end the loop
ShowWindowAsync(Process.GetProcessById(process.Id).MainWindowHandle, 2);
break;
}
// wait awhile
Thread.Sleep(100);
// place for another exit condition for example: loop running > 1min
}
}
I also posted this at stackoverflow as solution. I hope someone can use this snippet to save some time and if you think the code can be improved write me in the comments. I’m happy to hear your thoughts about it :)