1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

オートコンプリートと改行を実装したTextBox

Last updated at Posted at 2018-03-20

どこかのサイトからほぼ丸パクリしたけど、どこのサイトかわからなくなったのでメモ。


''' <summary>
''' マルチライン&オートコンプリートテキストボックス
''' </summary>
Public Class MultiLineAndAutoCompleteTextBox
    Inherits TextBox

    'Enterキー押下時にキャレット位置に改行を差し込むため
    Private CaretPos As Integer = 0

    'ReadOnlyにしたい。要検討。
    Public Overrides Property Multiline As Boolean
        Get
            Return False
        End Get
        Set(value As Boolean)
            MyBase.Multiline = False
        End Set
    End Property

    Protected Overrides ReadOnly Property CreateParams As CreateParams
        'このSecurity...の部分は特に丸パクリすぎて意味不明
        <Security.Permissions.SecurityPermission(Security.Permissions.SecurityAction.LinkDemand, Flags:=Security.Permissions.SecurityPermissionFlag.UnmanagedCode)>
        Get
            Dim cp As CreateParams = MyBase.CreateParams
            cp.Style = cp.Style Or 4
            Return cp
        End Get
    End Property

    'これをオーバーライドしている理由を失念。なくてもいいのかも。
    Public Overrides Property AutoSize As Boolean
        Get
            Return MyBase.AutoSize
        End Get
        Set(value As Boolean)
            MyBase.AutoSize = value
        End Set
    End Property

    Private Sub MyPrevKeyDown(sender As Object, e As PreviewKeyDownEventArgs) Handles MyBase.PreviewKeyDown
        If e.KeyCode = Keys.Enter Then
            CaretPos = SelectionStart
            Text = Text.Insert(CaretPos, Environment.NewLine)
        End If
    End Sub

    Private Sub MyKeyDown(sender As Object, e As KeyEventArgs) Handles MyBase.KeyDown
        If e.KeyCode = Keys.Enter Then
            Try
                '文法的にはMeをつけなくてもいいはずなのだが、つけないとSelect Caseだと誤解される。
                Me.Select(CaretPos + Environment.NewLine.Length, 0)
                ScrollToCaret()
            Catch ex As Exception
                '適切な処理
            End Try
        End If
    End Sub

オートコンプリートの設定は割愛。
どうしてもと要望があったので作った。
AutoSizeプロパティをFalseに設定して、Heightプロパティを適当な値に設定すると、それっぽくなったと思う。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?