ファイルのドラッグ&ドロップ
Windowsアプリケーション共通の操作の一つに、アプリケーション上にファイルをドラッグ&ドロップする操作があります。例えば、フォルダ上にファイルをドラッグ&ドロップしたり、Windows Media Player上に音楽ファイルをドラッグして再生したことがあるのではないでしょうか。
サンプルアプリケーションに手を加えて、ユーザーがWindowsエクスプローラから画像ファイルをドラッグして、PictureBoxコントロールにドロップできるようにしましょう。そのためには次の2つのステップが必要です。
- まず、
DragEnterイベントを修正します(リスト2を参照)。WindowsエクスプローラからドラッグされるファイルのデータタイプはFileDropです。従って、リスト2のコードでは、このデータタイプをDragEnterイベントハンドラでチェックします。 - 次に、
DragDropイベントをリスト3のように変更し、画像ファイルを開いてその内容をPictureBoxコントロールに表示できるようにします。
Private Sub PictureBox1_DragEnter( _ ByVal sender As Object, _ ByVal e As System.Windows.Forms. _ DragEventArgs) _ Handles PictureBox1.DragEnter Dim formats As String() = e.Data.GetFormats '---if the data to be dropped is an image format--- If (e.Data.GetDataPresent(DataFormats.Bitmap)) Then '---determine if this is a copy or move--- If (e.KeyState And CtrlMask) = CtrlMask Then e.Effect = DragDropEffects.Copy Else e.Effect = DragDropEffects.Move End If '---change the border style of the control--- PictureBox1.BorderStyle = BorderStyle.Fixed3D ElseIf (e.Data.GetDataPresent( _ DataFormats.FileDrop)) Then '---if this is a file drop--- e.Effect = DragDropEffects.All ElseIf (e.Data.GetDataPresent( _ DataFormats.Rtf)) Then '---determine if this is a copy or move--- If (e.KeyState And CtrlMask) = CtrlMask Then e.Effect = DragDropEffects.Copy Else e.Effect = DragDropEffects.Move End If '---change the border style of the control--- PictureBox1.BorderStyle = BorderStyle.Fixed3D End If End Sub
Private Sub PictureBox1_DragDrop( _ ByVal sender As Object, _ ByVal e As System.Windows.Forms.DragEventArgs) _ Handles PictureBox1.DragDrop '---if the data to be dropped is a image format--- If (e.Data.GetDataPresent(DataFormats.Bitmap)) Then '---set the control to ' display the bitmap being dropped--- PictureBox1.Image = e.Data.GetData( _ DataFormats.Bitmap) ElseIf (e.Data.GetDataPresent( _ DataFormats.FileDrop)) Then Dim files() As String files = e.Data.GetData( _ DataFormats.FileDrop) For Each file As String In files file = UCase(file) If file.EndsWith(".GIF") Or _ file.EndsWith(".JPG") Or _ file.EndsWith(".BMP") Then PictureBox1.Image = New Bitmap(file) End If System.Threading.Thread.Sleep(2000) Application.DoEvents() Next ElseIf (e.Data.GetDataPresent(DataFormats.Rtf)) Then '---display the rich text--- Console.WriteLine(e.Data.GetData( _ DataFormats.Rtf)) End If '---set the borderstyle back to its original--- PictureBox1.BorderStyle = BorderStyle.FixedSingle End Sub
必要な作業はこれだけです。これで、Windowsエクスプローラから画像ファイルをドラッグしてPictureBoxコントロールにドロップし、その内容を表示できます。今回変更したコードでは、PictureBoxコントロールに1つまたは複数のファイルをドロップできることに注意してください。複数ファイルをドロップした場合、それぞれの画像が2秒間隔で1つずつ表示されます。
