2

I have a basic Powershell form with a textbox. When I right-click on the textbox, a standard menu appears with copy, cut, paste etc...

My goal is to add a "clear log" option, that clears current textbox content. How can I add this option to right-click menu instead of doing/drawing an actual separate button?

Option will be enabled for this form only, I am not looking a general mouse-right-click solution from registry

igor
  • 248
  • 4
  • 16
  • To be able to show a ContextMenuStrip for a TextBox first you should set ShortcutsEnabled property of the TextBox to false, then assign a ContextMenuStrip to its ContextMenuStrip. – Reza Aghaei Dec 04 '17 at 07:15

2 Answers2

3

To be able to show a ContextMenuStrip for a TextBox first you should set ShortcutsEnabled property of the TextBox to false, then assign a ContextMenuStrip to its ContextMenuStrip property like this:

$form1= New-Object System.Windows.Forms.Form
$textBox1 = New-Object System.Windows.Forms.TextBox
$contextMenuStrip1 = New-Object System.Windows.Forms.ContextMenuStrip

$contextMenuStrip1.Items.Add("Item 1")
$contextMenuStrip1.Items.Add("Item 2")

$textBox1.ShortcutsEnabled = $false
$textBox1.ContextMenuStrip = $contextMenuStrip1

$form1.Text="Context Menu for TextBox"
$form1.Controls.Add($textBox1)

$form1.ShowDialog()
Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
  • Thanks, works as expected. Now I just doing an event function for Item1/2, as clicks, right? – igor Dec 04 '17 at 07:37
  • Btw, due line `$contextMenuStrip1.Items.Add` when running the script, in CMD I can see all item parameter. Do you know how to "silent" it? – igor Dec 04 '17 at 07:42
  • 1
    assign it to a variable or use `| Out-Null` to suppress the output. – Reza Aghaei Dec 04 '17 at 07:46
  • I love your answer here. I was trying to modify a little script using `ContextMenu` to use `ContexMenuStrip` to no avail, but now I can. – Nawad-sama Jan 16 '23 at 13:08
0

add [void] the start of $contextMenuStrip1.Items.Add

like so:

[void]$contextMenuStrip1.Items.Add($item)
David Buck
  • 3,752
  • 35
  • 31
  • 35
theo
  • 1