Close a window using the window handle

Is it possible to close a window if I have the window handle ?

My windowA has the properties :

handleB as integer
windowBopen as boolean

In windowA the action of a button is :

  if windowBopen = false then
    windowBopen = true
    dim TT as New windowB
    TT.show
    handleB = TT.Handle
  else
    ' close the open windowB that is already open
    windowB  ' .... needs to close the instance of windowB using its integer handle stored in property windowA.handleB
    windowBopen = false
  end if

You can loop over open windows to find a match

' close the open windowB that is already open for i As integer = 0 to WindowCount - 1 if Window(i).Handle = handleB then Window(i).Close exit end next windowBopen = false

You could also just store the window. Instead of windowBopen and handleB have “windowBRef As windowB”, then

[code]if windowBRef = nil then
windowBRef = New windowB
windowBRef.Show
else
windowBRef.Close
windowBRef = nil
end

//the old properties can be calculated as

windowBopen = (windowBRef <> nil)
handleB = windowBRef.Handle
[/code]

If WindowB can close on it’s own you’ll probably need to use WeakRef.

Thanks Will

Yes. At the moment I am using that method.

But I was hoping to be able to store some reference or handle of the instance of windowB in a property of windowA, rather than holding the Ref in a global variable, or having to loop through all the open windows to find the correct one.

But looking at your code :

are you saying that a handle of the Ref ( or even a handle of the instance of windowB ) can be stored in a windowA property ?

That seems to be back where I started, as I do not see how to close windowB using the handle integer value stored in the property.

WAIT A SEC

Now I see your point !

I can drop the windowA.handleB ( integer ) property and replace it with windowA.RefToB as windowB

Then when I create the new instance of windowB :

if windowBopen = false then
    windowBopen = true
    dim TT as New windowB
    TT.show
    RefToB = TT
  else
    ' close the open windowB that is already open
    RefToB.Close
    windowBopen = false
  end if

Thanks Will. That works !

or use a weak ref so that IF a person has manually closed the window your reference doesn’t keep it alive unnecessarily

Thanks Normal

windowB is a ‘plain box window’ and does not appear in the taskbar, so I think this method should be safe in this case.

I will definitely remember your suggestion for future.

Thank You

ah its application modal ?

Not modal. It is an options window that shows when a button is clicked. But it is not modal as I can still click on the button again to close it, or move the mouse pointer more that ‘x’ distance away, and it automatically closes again ( using X and Y in the MouseMove event of windowA ).