Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Find and Close the Window using Win API

0.00/5 (No votes)
19 Dec 2007 1  
Find and Close the window using Win API

Introduction

This article explains how to find and close the window using Win API .

Find and Close the Window

Find the Window

The FindWindow function retrieves a handle to the top-level window whose class name and window name match the specified strings. This function does not search child windows. This function does not perform a case-sensitive search.

FindWindow(string lpClassName,string lpWindowName) 

Finding ClassName and WindowName using Spy++

Spy++ (SPYXX.EXE) is a Win32-based utility that gives you a graphical view of the system's processes, threads, windows, and window messages. With the Window Finder Tool, you can find the properties of a selected window.

Step 1: Arrange your Windows so that Spy++ and the subject window are visible.

Step 2: From the Spy menu, choose Find Window to open the Find Window dialog box.

Step 3: Drag the Finder Tool to the desired window. As you drag the tool, window details display in the dialog box. (Handle, Caption(Window Name), Class Name)

using Microsoft.Win32;

[DllImport("user32.dll")]
        public static extern int FindWindow(string lpClassName,string lpWindowName);
        [DllImport("user32.dll")]
        public static extern int SendMessage(int hWnd, uint Msg, int wParam, int lParam);
            
        public const int WM_SYSCOMMAND = 0x0112;
        public const int SC_CLOSE = 0xF060;

private void closeWindow()
        {
            // retrieve the handler of the window  
            int iHandle = FindWindow("Notepad", "Untitled - Notepad");
            if (iHandle > 0)
            {
                // close the window using API        
                SendMessage(iHandle, WM_SYSCOMMAND, SC_CLOSE, 0);
            }  
        }	

History

  • 19th December, 2007: Initial post

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here