LoginSignup
0

More than 3 years have passed since last update.

テキストボックスでファイルをドロップ選択可能にする。

Posted at

テキストボックスの横に「参照」ボタンとかつくったり面倒なので
1行でファイルのドロップ選択できるテキストボックスを作るやつ用意しました。

作るやつ

BenriGoods.vb
Public Class BenriGoods
    Public Shared Sub SetFileDropTextBox(ByRef tbx As TextBox)
        Try
            tbx.AllowDrop = True
            'ファイルが一つであればファイルパスを読み込み対象テキストへ反映
            AddHandler tbx.DragDrop, New DragEventHandler(
                Sub(sender As Object, e As DragEventArgs)
                    Dim fileName As String() = CType(e.Data.GetData(DataFormats.FileDrop, False), String())
                    If fileName.Length = 1 Then
                        CType(sender, TextBox).Text = fileName(0)
                    End If
                End Sub)

            'ファイルが一つであればカーソル色変更(複数ファイルは無視)
            AddHandler tbx.DragEnter, New DragEventHandler(
                Sub(sender As Object, e As DragEventArgs)
                    Dim fileName As String() = CType(e.Data.GetData(DataFormats.FileDrop, False), String())
                    If fileName.Length = 1 Then
                        e.Effect = DragDropEffects.Copy
                    End If
                End Sub)
        Catch ex As Exception
        End Try
    End Sub
End Class

使い方

FormUNKO.vb
BenriGoods.SetFileDropTextBox(textboxUnko) 'テキストボックスを引数に与える

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
0