using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; //weird callback method, like pointers in C#, pretty cool stuff! public delegate bool CallBack(int hWnd, int lParam); namespace KillOneNote { /* Thanks to: * http://www.codeproject.com/csharp/cskillapp.asp * & http://www.c-sharpcorner.com/Code/2002/Nov/win32api.asp * & http://www.vbaccelerator.com/home/net/code/Libraries/Windows/Enumerating_Windows/article.asp * & http://www.codeproject.com/csharp/runninginstanceie.asp <-- good! */ class OneNoteWindowFinder { //delcare the external methods that are imported from the user32.dll library [DllImport("user32.Dll")] public static extern int EnumWindows(CallBack x, int y); [DllImport("User32.Dll")] public static extern void GetWindowText(int h, StringBuilder s, int nMaxCount); [DllImport("User32.Dll")] public static extern void GetClassName(int h, StringBuilder s, int nMaxCount); [DllImport("User32.Dll")] public static extern IntPtr PostMessage(IntPtr hWnd, int msg, int wParam, int lParam); //a list for all of my windows..see my 'class' (actually a struct below) //static because I need to have other methods access this private static List all_windows; public List All_windows { get { return all_windows; } } public OneNoteWindowFinder() { all_windows = new List(); getWindows(); } public void getWindows() { //calls the user32.dll EnumWindows and goes to my CallBack method (delcared @ the top) EnumWindows(new CallBack(OneNoteWindowFinder.EnumWindowCallBack), 0); } //now this is called by the EunmWindows and it needs to be static and so it the all_windows above private static bool EnumWindowCallBack(int hWnd, int lParam) { StringBuilder sWText = new StringBuilder(1024); StringBuilder sWClass = new StringBuilder(256); //get the window text & window class type GetWindowText(hWnd, sWText, sWText.Capacity); GetClassName(hWnd, sWClass, sWClass.Capacity); //look for OneNote in the title and also our type which is Framework::CFrame if (sWText.ToString().Contains("Microsoft Office OneNote") && sWClass.ToString().Equals("Framework::CFrame")) { OneNoteWindowFinder.all_windows.Add(new ONWindow(hWnd, sWText.ToString())); } return true; } public void Kill(int hWnd) { int kill_msg = 0x0010; /* WM_CLOSE */ //call the user32.dll method for this PostMessage((IntPtr)hWnd, kill_msg, 0, 0); } } //my basic class to hold the hWnd & title class ONWindow { String title; int hWnd; public int HWnd { get { return hWnd; } } public String Title { get { return title; } } public ONWindow(int in_hWnd, String sb) { hWnd = in_hWnd; title = sb; } //just in case you want it! public string toString() { return ("hWnd: " + hWnd + "\tTitle: " + title); } } class Program { static void Main(string[] args) { OneNoteWindowFinder onFinder = new OneNoteWindowFinder(); foreach (ONWindow onw in onFinder.All_windows) { System.Console.WriteLine(onw.toString()); onFinder.Kill(onw.HWnd); } } } }