using the X to close a window?

rated by 0 users
This post has 0 Replies | 1 Follower

Top 100 Contributor
Posts 24
Sven Posted: 08-22-2013 7:36 AM

Hi,

I created a window that disappears in several different ways. I can type a valid path, I can press the "Cancel" Button, I can press the Escape Key. But if I press the X the window comes back. Is there a way to catch the "X" from within a .NET window?

Here is the code:

function CustomInputBox([string] $title, [string] $message, [string] $defaultText) {
 
    [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
    [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")

    $objForm = New-Object System.Windows.Forms.Form
    $objForm.Text = "$title"
    $objForm.Size = New-Object System.Drawing.Size(300,200)
    $objForm.StartPosition = "CenterScreen"

    $objForm.KeyPreview = $True
    $objForm.Add_KeyDown({if ($_.KeyCode -eq "Enter")
        {$script:_userinput=$objTextBox.Text;$objForm.Close()}})
    $objForm.Add_KeyDown({if ($_.KeyCode -eq "Escape")
        {$script:_userinput="Cancel";$objForm.Close()}})

    $OKButton = New-Object System.Windows.Forms.Button
    $OKButton.Location = New-Object System.Drawing.Size(75,120)
    $OKButton.Size = New-Object System.Drawing.Size(75,23)
    $OKButton.Text = "OK"
    $OKButton.Add_Click({$script:_userinput=$objTextBox.Text;$objForm.Close()})
    $objForm.Controls.Add($OKButton)

    $CancelButton = New-Object System.Windows.Forms.Button
    $CancelButton.Location = New-Object System.Drawing.Size(150,120)
    $CancelButton.Size = New-Object System.Drawing.Size(75,23)
    $CancelButton.Text = "Cancel"
    $CancelButton.Add_Click({$script:_userinput="Cancel";$objForm.Close()})
    $objForm.Controls.Add($CancelButton)

    $objLabel = New-Object System.Windows.Forms.Label
    $objLabel.Location = New-Object System.Drawing.Size(10,20)
    $objLabel.Size = New-Object System.Drawing.Size(280,20)
    $objLabel.Text = "$message"
    $objForm.Controls.Add($objLabel)

    $objTextBox = New-Object System.Windows.Forms.TextBox
    $objTextBox.Location = New-Object System.Drawing.Size(10,40)
    $objTextBox.Size = New-Object System.Drawing.Size(260,20)
    $objForm.Controls.Add($objTextBox)
 
    $objForm.Topmost = $True

    $objForm.Add_Shown({$objForm.Activate()})
    [void] $objForm.ShowDialog()
   
 
 
 return $_userInput
}

The X writes it's output to $objForm.Dialogresult. So what I want is something like the Cancel-Button or Escape-Key. I guess the X closes the window itself. But I also need the output from $objForm.DialogResult as my return value because otherwise I can't escape the do - while loop that opens the dialog window.

I tried it in several ways but nothing works... any idea?

Thank you

Sven

 

Page 1 of 1 (1 items) | RSS
Copyright 2012 PowerShell.com. All rights reserved.