主要利用SmTextBox控件的SelectedText、SelectionStart和SelectionLength三个属性。正常在编辑状态下,这三个属性可能很正常,但是一旦SmTextBox控件失去焦点,比如点击某个命令按钮,或者切换到其他控件时,这三个属性的值会丢失。所以我们想正常处理就需要在控件的Leave事件中保存SelectionStart和SelectionLength这两个属性的值,最后在赋值插入字符时再使用。
- Public Class Formb01bb1712f52406cafdb5e9413171eac
- Inherits FormEventsBase
-
- Private btnWhere As SmButton
- Private btnFrom As SmButton
- Private btnSelect As SmButton
- Private SmLabel1 As SmLabel
- Private SmTextBox1 As SmTextBox
- Public Sub TextBox插入文本_Load(sender As Object,e As System.EventArgs)
- btnWhere=Me.SmForm.ControlDictionary()("btnWhere")
- btnFrom=Me.SmForm.ControlDictionary()("btnFrom")
- btnSelect=Me.SmForm.ControlDictionary()("btnSelect")
- SmLabel1=Me.SmForm.ControlDictionary()("SmLabel1")
- SmTextBox1=Me.SmForm.ControlDictionary()("SmTextBox1")
-
- End Sub
-
- Public Sub btnSelect_Click(sender As Object,e As System.EventArgs)
- Dim btn As SmButton=sender
- '为了让插入文本有可持续性,我们需要先激活SmTextBox控件
- SmTextBox1.Select
- '先将选择起始位和选择长度赋值,这样就可以恢复TextBox的选择状态
- SmTextBox1.SelectionStart=_SelectionStart
- SmTextBox1.SelectionLength=_SelectionLength
- '替换相应的选择文本。什么都没有选择的时候就会插入
- SmTextBox1.SelectedText=btn.Text
-
- End Sub
- '定义两个私有字段,用来存储因为控件离开时TextBox的选择状态丢失的问题。
- Private _SelectionStart As Integer=0
- Private _SelectionLength As Integer=0
- Public Sub SmTextBox1_Leave(sender As Object,e As System.EventArgs)
- '将TextBox控件的选择状态记录下来
- _SelectionStart=SmTextBox1.SelectionStart
- _SelectionLength=SmTextBox1.SelectionLength
- End Sub
-
- End Class
复制代码
附件是窗体文件,可以导入试试效果。
|