You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell GUI多行TextBox操作后保持光标在起始位置问题求助

解决PowerShell WinForms多行TextBox清空后光标定位到起始位置的问题

要实现清空TextBox后光标停在第一行起始位置,只需在清空文本后手动设置光标位置,并确保控件获得焦点。同时还需要修复回车触发时的默认行为,避免意外添加换行。

修改后的核心逻辑

在ButtonClick函数中添加光标定位和焦点设置代码,同时在回车事件中抑制默认按键行为:

Function ButtonClick
{
    $test = $textBoxDisplay.Text
    Invoke-RestMethod -Method Post -ContentType 'Application/Json' -Body "{`"text`":`"$test`"}" -Uri $myTeamsWebhook
    
    $textBoxDisplay.Clear()
    # 定位光标到起始位置
    $textBoxDisplay.SelectionStart = 0
    $textBoxDisplay.SelectionLength = 0
    # 确保TextBox获得焦点
    $textBoxDisplay.Focus()
}

$textBoxDisplay.add_KeyDown({
    if ($_.KeyCode -eq "Enter"){
        ButtonClick
        # 取消Enter键默认换行行为
        $_.SuppressKeyPress = $true
    }
})

完整修改后的代码

Add-Type -AssemblyName System.Windows.Forms

Function ButtonClick
{
    $test = $textBoxDisplay.Text
    Invoke-RestMethod -Method Post -ContentType 'Application/Json' -Body "{`"text`":`"$test`"}" -Uri $myTeamsWebhook
    $textBoxDisplay.Clear()
    # 设置光标到起始位置
    $textBoxDisplay.SelectionStart = 0
    $textBoxDisplay.SelectionLength = 0
    # 确保TextBox获得焦点
    $textBoxDisplay.Focus()
}

$myTeamsWebhook = 'xxx'


[System.Windows.Forms.Application]::EnableVisualStyles()
$button = New-Object 'System.Windows.Forms.Button'
$button.Location = '10, 10'
$button.Name = "buttonGo"
$button.Size = '75, 25'
$button.TabIndex = 0
$button.Text = "&Go"
$button.UseVisualStyleBackColor = $true
$button.Add_Click({ButtonClick})

$textBoxDisplay = New-Object 'System.Windows.Forms.TextBox'
$textBoxDisplay.Location = '12, 50'
$textBoxDisplay.Multiline = $true
$textBoxDisplay.Name = "textBoxDisplay"
$textBoxDisplay.Size = '470, 150'
$textBoxDisplay.TabIndex = 1
$textBoxDisplay.Focus()
$textBoxDisplay.AcceptsReturn = $false
$textBoxDisplay.WordWrap = $true

$textBoxDisplay.add_KeyDown({
    if ($_.KeyCode -eq "Enter"){
        ButtonClick
        # 取消Enter键的默认行为
        $_.SuppressKeyPress = $true
    }
})


$mainForm = New-Object 'System.Windows.Forms.Form'
$mainForm.Size = '500, 250'
$mainForm.Controls.Add($button)
$mainForm.Controls.Add($textBoxDisplay)
$mainForm.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedDialog
$mainForm.Name = "mainForm"
$mainForm.Text = "GUI Test"

$mainForm.ShowDialog()

关键说明

  • SelectionStart = 0:将光标定位到文本的第0个字符位置(即第一行开头)
  • SelectionLength = 0:确保无文本选中,光标以插入模式显示
  • Focus():清空文本后可能丢失焦点,强制让TextBox重新获得焦点保证光标可见
  • SuppressKeyPress = $true:阻止Enter键默认换行行为,避免光标跳到第二行

内容的提问来源于stack exchange,提问作者Nawad-sama

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 21:55:26