Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

winapi

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.

like image 975
0x90 Avatar asked Dec 14 '11 15:12

0x90


People also ask

How do I close a window in Javascript?

To close your current window using JS, do this. First open the current window to trick your current tab into thinking it has been opened by a script. Then close it using window. close().

How do I close the HTML window automatically?

open("URL_HERE", "my_window", "height=100,width=100"); and we need to close the second page automatically after login success. Okay so in the popup use window. close() to close the window like I mentoined in my example.

What is a handle to a window?

A handle is a unique identifier for an object managed by Windows. It's like a pointer, but not a pointer in the sence that it's not an address that could be dereferenced by user code to gain access to some data.


1 Answers

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.

like image 147
David Heffernan Avatar answered Oct 26 '22 09:10

David Heffernan