Windows close window by handle

CloseHandle function (handleapi.h)

Closes an open object handle.

Syntax

Parameters

A valid handle to an open object.

Return value

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

If the application is running under a debugger, the function will throw an exception if it receives either a handle value that is not valid or a pseudo-handle value. This can happen if you close a handle twice, or if you call CloseHandle on a handle returned by the FindFirstFile function instead of calling the FindClose function.

Remarks

The CloseHandle function closes handles to the following objects:

  • Access token
  • Communications device
  • Console input
  • Console screen buffer
  • Event
  • File
  • File mapping
  • I/O completion port
  • Job
  • Mailslot
  • Memory resource notification
  • Mutex
  • Named pipe
  • Pipe
  • Process
  • Semaphore
  • Thread
  • Transaction
  • Waitable timer

The documentation for the functions that create these objects indicates that CloseHandle should be used when you are finished with the object, and what happens to pending operations on the object after the handle is closed. In general, CloseHandle invalidates the specified object handle, decrements the object’s handle count, and performs object retention checks. After the last handle to an object is closed, the object is removed from the system. For a summary of the creator functions for these objects, see Kernel Objects.

Generally, an application should call CloseHandle once for each handle it opens. It is usually not necessary to call CloseHandle if a function that uses a handle fails with ERROR_INVALID_HANDLE, because this error usually indicates that the handle is already invalidated. However, some functions use ERROR_INVALID_HANDLE to indicate that the object itself is no longer valid. For example, a function that attempts to use a handle to a file on a network might fail with ERROR_INVALID_HANDLE if the network connection is severed, because the file object is no longer available. In this case, the application should close the handle.

If a handle is transacted, all handles bound to a transaction should be closed before the transaction is committed. If a transacted handle was opened by calling CreateFileTransacted with the FILE_FLAG_DELETE_ON_CLOSE flag, the file is not deleted until the application closes the handle and calls CommitTransaction. For more information about transacted objects, see Working With Transactions.

Closing a thread handle does not terminate the associated thread or remove the thread object. Closing a process handle does not terminate the associated process or remove the process object. To remove a thread object, you must terminate the thread, then close all handles to the thread. For more information, see Terminating a Thread. To remove a process object, you must terminate the process, then close all handles to the process. For more information, see Terminating a Process.

Closing a handle to a file mapping can succeed even when there are file views that are still open. For more information, see Closing a File Mapping Object.

Читайте также:  Прямой эфир инстаграм windows

Do not use the CloseHandle function to close a socket. Instead, use the closesocket function, which releases all resources associated with the socket including the handle to the socket object. For more information, see Socket Closure.

Do not use the CloseHandle function to close a handle to an open registry key. Instead, use the RegCloseKey function. CloseHandle does not close the handle to the registry key, but does not return an error to indicate this failure.

Closing the Window

When the user closes a window, that action triggers a sequence of window messages.

The user can close an application window by clicking the Close button, or by using a keyboard shortcut such as ALT+F4. Any of these actions causes the window to receive a WM_CLOSE message. The WM_CLOSE message gives you an opportunity to prompt the user before closing the window. If you really do want to close the window, call the DestroyWindow function. Otherwise, simply return zero from the WM_CLOSE message, and the operating system will ignore the message and not destroy the window.

Here is an example of how a program might handle WM_CLOSE.

In this example, the MessageBox function shows a modal dialog that contains OK and Cancel buttons. If the user clicks OK, the program calls DestroyWindow. Otherwise, if the user clicks Cancel, the call to DestroyWindow is skipped, and the window remains open. In either case, return zero to indicate that you handled the message.

If you want to close the window without prompting the user, you could simply call DestroyWindow without the call to MessageBox. However, there is a shortcut in this case. Recall that DefWindowProc executes the default action for any window message. In the case of WM_CLOSE, DefWindowProc automatically calls DestroyWindow. That means if you ignore the WM_CLOSE message in your switch statement, the window is destroyed by default.

When a window is about to be destroyed, it receives a WM_DESTROY message. This message is sent after the window is removed from the screen, but before the destruction occurs (in particular, before any child windows are destroyed).

In your main application window, you will typically respond to WM_DESTROY by calling PostQuitMessage.

We saw in the Window Messages section that PostQuitMessage puts a WM_QUIT message on the message queue, causing the message loop to end.

Here is a flow chart showing the typical way to process WM_CLOSE and WM_DESTROY messages:

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.

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

And I’m getting the error

What am I missing?

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

Читайте также:  Как отключить автономный установщик обновлений windows

3 Answers 3

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.

Window. Closing Событие

Определение

Происходит непосредственно после вызова метода Close() и может быть обработано с отменой закрытия окна. Occurs directly after Close() is called, and can be handled to cancel window closure.

Тип события

Исключения

Задано свойство Visibility либо вызван один из методов Show(), ShowDialog() или Close() во время закрытия окна. Visibility is set, or Show(), ShowDialog(), or Close() is called while a window is closing.

Примеры

В следующем примере демонстрируется Window , что определяет, требуется ли для закрытия вмешательство пользователя. The following example demonstrates a Window that determines whether it needs user intervention to close.

Комментарии

Closing может обрабатываться для обнаружения закрытия окна (например, при Close вызове). Closing can be handled to detect when a window is being closed (for example, when Close is called). Кроме того, Closing можно использовать, чтобы предотвратить закрытие окна. Furthermore, Closing can be used to prevent a window from closing. Чтобы предотвратить закрытие окна, можно присвоить Cancel свойству CancelEventArgs аргумента значение true . To prevent a window from closing, you can set the Cancel property of the CancelEventArgs argument to true .

ClosingСобытие возникает при Close вызове, если нажата кнопка закрытия окна или если пользователь нажмет Alt + F4. The Closing event is raised when Close is called, if a window’s Close button is clicked, or if the user presses ALT+F4.

Если принадлежащее окно было открыто окном-владельцем с помощью Show , а окно владельца закрыто, событие принадлежащего окна Closing не вызывается. If an owned window was opened by its owner window using Show, and the owner window is closed, the owned window’s Closing event is not raised. Если владелец окна закрыт (см Owner . раздел), Closing в принадлежащем окне не создается. If the owner of a window is closed (see Owner), Closing is not raised on the owned window.

Читайте также:  Ordering windows by size

При Shutdown вызове метода вызывается Closing событие для каждого окна. If Shutdown is called, the Closing event for each window is raised. Однако если операция Closing отменена, то отмена игнорируется. However, if Closing is canceled, cancellation is ignored.

Значение, если сеанс завершается из-за того, что пользователь выходит из системы или завершает работу, Closing не вызывается; обрабатывается SessionEnding для реализации кода, который отменяет закрытие приложения. If a session ends because a user logs off or shuts down, Closing is not raised; handle SessionEnding to implement code that cancels application closure.

Если вы хотите отображать и скрывать окно несколько раз в течение всего времени существования приложения и вы не хотите повторно создавать экземпляры окна при каждом его отображении, можно обойти Closing событие, отменить его и вызвать Hide метод. If you want to show and hide a window multiple times during the lifetime of an application, and you don’t want to reinstantiate the window each time you show it, you can handle the Closing event, cancel it, and call the Hide method. Затем можно вызвать в Show том же экземпляре, чтобы снова открыть его. Then, you can call Show on the same instance to reopen it.

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.

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

And I’m getting the error

What am I missing?

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

3 Answers 3

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.

Оцените статью