画像のドラッグ&ドロップ(2)
さまざまなデータタイプのハンドリング
作成済みのDragEnterイベントに、次の太字で示した行を追加します。GetFormats()メソッドは、イベントに渡されるデータのタイプを返します。
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 ...
イベントに渡されるデータのタイプを監視するために、ここで追加した行の後にブレークポイントを設定します。F5キーを押してアプリケーションをデバッグ実行し、WordからPictureBoxコントロールに画像をドロップしてみましょう。図6は、Wordからドラッグ&ドロップされた画像のデータタイプを示しています。

この図から、考えられるフォーマットの1つがビットマップであることが分かります。従って、データを無事にビットマップ画像に変換して、PictureBoxコントロールに表示できます。これに対して、ワードパッドから画像をドラッグ&ドロップしたときのデータタイプは図7のように示されます。

今度は、画像データがビットマップ形式で渡されていません。その代わりに、RTF(リッチテキストフォーマット)で渡されています。
従って、ワードパッドからドラッグ&ドロップされた画像をPictureBoxコントロールで受け取れるようにするには、ビットマップだけでなくRTFも受けつけるようにDragEnterイベントを変更する必要があります。
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.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
さらに、DragDropイベントを修正して、このデータフォーマットを処理するカスタムコードを記述します。
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 text being dropped--- PictureBox1.Image = e.Data.GetData( _ DataFormats.Bitmap) 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
残念ながら、このコードで行っているのは、画像データを単にRTFとしてコンソールウィンドウに書き出すことだけです(図8を参照)。PictureBoxコントロールに実際の画像を表示するには、画像データを抽出するコードを記述する必要があります。

