本文介绍了在 VB.NET 中如何实现接受拖放的文件,即从资源管理器中拖放到应用程序中的时候,自动获取拖放的文件。文中的例子是一个接受拖放文件显示文件内容的 VB.NET 实例程序。
引言:
对于文本格式的文件,我们可以直接拖到记事本中就可以看到内容;各种类型的图片,拖到 Photoshop 中,就可以直接对其编辑。我们如何在 VB.NET 开发的程序也实现上述效果呢?
思路:
我们知道,每一个 Windows 的应用程序都有一个消息队列,程序的主体接受系统的消息,然后分发出去(给一个 form ,或者一个控件),接受者有相应的程序来处理消息。在 .NET 的 Form 中,默认情况下程序是不翻译这些消息的,也就是说默认我们的 Class 是不加入应用程序的消息泵。能不能把我们的 Form Class 加入应用程序的消息泵呢?可以!
在 .NET 中,任何一个实现 ** IMessageFilter ** 接口的类,可以添加到应用程序的消息泵中,以在消息被调度到控件或窗体之前将它筛选出来或执行其他操作。使用 Application 类中的 AddMessageFilter 方法,可以将消息筛选器添加到应用程序的消息泵中。
于是我们在程序加载的时候,调用 Application.AddMessageFilter(Me) 。然而,默认情况下一个 Form 或者控件是不能接受拖放的文件的,我们调用一个 WIN32 API DragAcceptFiles ,这个 API 可以设置对应的控件是否能接受拖放的文件。然后可以用 DragQueryFile 查询拖放到的文件列表,也就是拖放文件地具体路径和文件名。 ** **
代码:
Imports System.Runtime.InteropServices
Public Class Form1
Inherits System.Windows.Forms.Form
Implements IMessageFilter
‘ API申明
Const WM_DROPFILES = &H233 ‘ 拖放文件消息
1<dllimport("shell32.dll")> Public Shared Sub DragFinish( ByVal hDrop As Integer )
2
3End Sub
4
5<dllimport("shell32.dll")> Public Shared Sub DragAcceptFiles( ByVal hwnd As Integer , ByVal fAccept As Boolean )
6
7End Sub
8
9<dllimport("shell32.dll")> Public Shared Function DragQueryFile( ByVal HDROP As Integer , ByVal UINT As Integer , ByVal lpStr As System.Text.StringBuilder, ByVal ch As Integer ) As Integer
10
11End Function
12
13---
14
15Private Sub Form1_Load( ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase .Load
16
17Application.AddMessageFilter( Me )
18
19DragAcceptFiles(TextBox1.Handle.ToInt32, True )
20
21End Sub
22
23Function PreFilterMessage( ByRef m As Message) As Boolean Implements IMessageFilter.PreFilterMessage
24
25If m.Msg = WM_DROPFILES Then
26
27'设置拖放的动作
28
29Dim nfiles As Int16
30
31nfiles = DragQueryFile(m.WParam.ToInt32, -1, Nothing , 0)
32
33Dim i As Int16
34
35Dim sb As New System.Text.StringBuilder(256)
36
37Dim sFirstFileName As String '记录第一个文件名
38
39TextBox1.Clear()
40
41For i = 0 To nfiles - 1
42
43DragQueryFile(m.WParam.ToInt32, i, sb, 256)
44
45If i = 0 Then sFirstFileName = sb.ToString
46
47TextBox1.AppendText(ControlChars.CrLf & sb.ToString)
48
49Next
50
51DragFinish(m.WParam.ToInt32) '拖放完成
52
53'显示文件内容
54
55Dim fs As New System.IO.FileStream(sFirstFileName, IO.FileMode.Open)
56
57Dim sr As New System.IO.StreamReader(fs, System.Text.Encoding.GetEncoding("gb2312"))
58
59TextBox1.AppendText(ControlChars.CrLf & sr.ReadToEnd().ToString)
60
61fs.Close()
62
63sr.Close()
64
65End If
66
67Return False
68
69End Function
70
71Protected Overloads Overrides Sub Dispose( ByVal disposing As Boolean )
72
73If disposing Then
74
75If Not (components Is Nothing ) Then
76
77components.Dispose()
78
79End If
80
81End If
82
83Application.RemoveMessageFilter( Me )
84
85DragAcceptFiles(TextBox1.Handle.ToInt32, False )
86
87MyBase .Dispose(disposing)
88
89End Sub
90
91注意:拖放结束后,调用 DragFinish 释放内存。</dllimport("shell32.dll")></dllimport("shell32.dll")></dllimport("shell32.dll")>