Close a Running Windows Application

Problem

As part of some of your large Access applications, you often allow users to start other Windows tools (Notepad, Calculator, Calendar, etc.); once those tools are open, your application doesn’t touch them. Some users have complained about all the “junk” left over once your application closes. Is there some way you can close another window from your Access application? That way, on the way out you can close any tools your application has opened.

Solution

Section 11.9.2 demonstrated the retrieval of a list of all the running Windows applications’ captions, class names, and window handles. Once you know that information, it’s easy to close an application: given a window handle, simply tell it to close. Using the Windows API PostMessage function, you can close any window at any time. Of course, some applications (those that support Automation; see Chapter 12 for more information) allow themselves to be closed programmatically without using the Windows API. Other applications that don’t support Automation will require either the API method described here, or SendKeys, which is unreliable at best.

Load and run frmListWindows from 11-10.MDB. This form, shown in Figure 11-12, is similar to the sample form in Section 11.9.2 with the addition of the Stop App button, which lets you close the selected window. Try a few; you can even close Access this way, if you want.

Figure 11-12. frmListWindows includes a Stop App button

Warning

Some top-level windows ...

Get Access Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.