Closing OneNote programmatically / OneNote Close API

The other day I was in a conference call and someone asked if you could close OneNote via the API.  In fact you cannot do this via the API but when I was talking to some of the developers for the team they said that you could just send Windows messages to OneNote telling it to close.  Well I thought that sounded like a good idea.  I am no expert on how to program this so I set out this evening to learn how to do this and do it with C# since I think that is what most developers will be using to program with OneNote.

 

I knew to start off looking for stuff about FindWindow which was in the user32.dll library and I knew about SendMessage as well but I wasn't sure how I was going to get this.  I first landed on this page: Kill any application with system menu using C# - The Code Project - C# Programming.  However this was if you knew the name of your application and the problem is that OneNote might have a few of them open so I had to keep searching.  I then went to MSDN: EnumWindows Function which looked promising since I wanted to use this.  However MSDN didn't have any code samples for this : (

Then I ended up here Enumerating Windows which had some good information but not quite what I was looking for.  Then I found this page:Capturing the Running IE Instances in C#.  This had some great information.

So I ended up with the following code, okay well I just found out that you can't easily post code on a blog...grrr this sucks.  Please get the file here: KillOneNote.

If you have questions please let me know and I hope this works for you!