0x90
0x90

Reputation: 40982

Why can't I close the window handle in my code?

I have these two lines in my main, but I can not close the the handle in the end. I am trying to get a handle to windows mines weeper and close it after that, but it doesn't work. And I have all the relevant includes I need.

#include <windows.h>
#include <stdio.h>

in the main

HWND wh = FindWindow("Minesweeper", "Minesweeper");
CloseHandle(wh);

On the printf of wh I see the value is identical to this raised in spy++.

And I'm getting the error

"Exception address: 0x7c90e4ff"

What am I missing?

BTW: Closing Handle of a process works fine if I change the two lines above.

Upvotes: 7

Views: 6376

Answers (5)

Willy
Willy

Reputation: 11

For me, EndModal is a working solution:

HWND hWnd = GetWindow(Handle, GW_ENABLEDPOPUP);
EndDialog(hWnd, IntPtr.Zero);

Upvotes: 1

ScienceDiscoverer
ScienceDiscoverer

Reputation: 202

If you want to close specific sub-window of some other process, and not just kill whole process with WM_CLOSE you can inject your code into another process and call DestroyWindow from there. This will also let you close windows that are specifically ignoring WM_CLOSE messages or not responding.

Upvotes: 0

kol
kol

Reputation: 28678

Do not use CloseHandle, CloseWindow or DestroyWindow. Send a WM_CLOSE message to the window using SendMessage.

Upvotes: 6

David Heffernan
David Heffernan

Reputation: 612794

There are a couple of basic problems here. First of all you don't call CloseHandle with a window handle. It's not that kind of handle. You use CloseHandle when you have a HANDLE but an HWND is not a HANDLE. If you want to destroy a window handle you need to call DestroyWindow.

However, the documentation for DestroyWindow states:

A thread cannot use DestroyWindow to destroy a window created by a different thread.

So you can't do that either.

What you can do is to send a WM_CLOSE message to the window. That should be enough to persuade it to close gracefully.

Note that WM_CLOSE is sent rather than posted. This can be discerned by this line from the documentation:

A window receives this message through its WindowProc function.

Update

John Knoller points out that I am misinterpreting the Windows documentation which was not written to cover the situation where one application attempts to close down another application.

John's advice is:

In fact it's wiser to send WM_CLOSE to another process using PostMessage or SendNotifyMessage. If you use SendMessage, you will get stuck if the process isn't pumping messages. It's even better to use WM_SYSCOMMAND/SCCLOSE which is basically the same thing as clicking on the window caption's close button.

Upvotes: 16

Bukes
Bukes

Reputation: 3708

Windows handles (HWNDs) are not system handles (HANDLEs). CloseHandle() is for system objects.

Consider PostMessage( wh, WM_CLOSE, 0, 0 );, as this article describes.

Upvotes: 4

Related Questions