Home > other >  Create Powershell form where button makes text to speech
Create Powershell form where button makes text to speech

Time:09-17

I'm trying to combine two different things in PowerShell that I have no experience with. Creating a form and text to speech. For the text to speech, I've verified that this will talk to me:

Add-Type -AssemblyName System.speech

$speak = New-Object System.Speech.Synthesis.SpeechSynthesizer
$speak.Speak('My test speech')

In my Google searches, I've found some info on creating text boxes. As an example, this will create a box with just a cancel button:

    Add-Type -AssemblyName System.Windows.Forms
    Add-Type -AssemblyName System.Drawing

    $form = New-Object System.Windows.Forms.Form
    $form.Text = 'Data Entry Form'
    $form.Size = New-Object System.Drawing.Size(300,200)
    $form.StartPosition = 'CenterScreen'

    $cancelButton = New-Object System.Windows.Forms.Button
    $cancelButton.Location = New-Object System.Drawing.Point(150,120)
    $cancelButton.Size = New-Object System.Drawing.Size(75,23)
    $cancelButton.Text = 'Cancel'
    $cancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
    $form.CancelButton = $cancelButton
    $form.Controls.Add($cancelButton)

    $result = $form.ShowDialog()

My hope is to create a button that will read the text I have specified, but I'm struggling to figure that out. I've edited it to this:

    Add-Type -AssemblyName System.speech

    $speak = New-Object System.Speech.Synthesis.SpeechSynthesizer

    Add-Type -AssemblyName System.Windows.Forms
    Add-Type -AssemblyName System.Drawing

    $form = New-Object System.Windows.Forms.Form
    $form.Text = 'Data Entry Form'
    $form.Size = New-Object System.Drawing.Size(300,200)
    $form.StartPosition = 'CenterScreen'

    $speakButton = New-Object System.Windows.Forms.Button
    $speakButton.Location = New-Object System.Drawing.Point(150,120)
    $speakButton.Size = New-Object System.Drawing.Size(75,23)
    $speakButton.Text = 'Speak'
    $speakButton.DialogResult = [System.Windows.Forms.DialogResult]$speak.Speak('My test speech')
    $form.text = $speakButton
    $form.Controls.Add($speakButton)

    $result = $form.ShowDialog()

When I start this it says "My test speech" before the box pops up, and nothing happens when I click the button. Clearly I'm on the wrong path here, but I'm not sure where the right one is.

CodePudding user response:

You'll want to register an event handler for the button's Click event, which in PowerShell can be done like this:

$speakButton.add_Click({
    $speak.Speak('My test speech')
})

And then remove the assignment to $speakButton.DialogResult

To use a textbox as input, replace the literal string value with a reference to the Text field on the text box control you want to read from:

$speakButton.add_Click({
    $speak.Speak($variableContainingTextBoxControl.Text)
})
  • Related