在VB.NET中實(shí)現(xiàn)文件的拖放
2024-07-10 13:01:08
供稿:網(wǎng)友
本文介紹了在vb.net中如何實(shí)現(xiàn)接受拖放的文件,即從資源管理器中拖放到應(yīng)用程序中的時候,自動獲取拖放的文件。文中的例子是一個接受拖放文件顯示文件內(nèi)容的vb.net實(shí)例程序。
引言:
對于文本格式的文件,我們可以直接拖到記事本中就可以看到內(nèi)容;各種類型的圖片,拖到photoshop中,就可以直接對其編輯。我們?nèi)绾卧趘b.net開發(fā)的程序也實(shí)現(xiàn)上述效果呢?
思路:
我們知道,每一個windows的應(yīng)用程序都有一個消息隊(duì)列,程序的主體接受系統(tǒng)的消息,然后分發(fā)出去(給一個form,或者一個控件),接受者有相應(yīng)的程序來處理消息。在.net的form中,默認(rèn)情況下程序是不翻譯這些消息的,也就是說默認(rèn)我們的class是不加入應(yīng)用程序的消息泵。能不能把我們的form class加入應(yīng)用程序的消息泵呢?可以!
在.net中,任何一個實(shí)現(xiàn)imessagefilter 接口的類,可以添加到應(yīng)用程序的消息泵中,以在消息被調(diào)度到控件或窗體之前將它篩選出來或執(zhí)行其他操作。使用 application 類中的 addmessagefilter 方法,可以將消息篩選器添加到應(yīng)用程序的消息泵中。
于是我們在程序加載的時候,調(diào)用application.addmessagefilter(me)。然而,默認(rèn)情況下一個form或者控件是不能接受拖放的文件的,我們調(diào)用一個win32 api dragacceptfiles,這個api可以設(shè)置對應(yīng)的控件是否能接受拖放的文件。然后可以用dragqueryfile查詢拖放到的文件列表,也就是拖放文件地具體路徑和文件名。
代碼:
imports system.runtime.interopservices
public class form1
inherits system.windows.forms.form
implements imessagefilter
‘ api申明
const wm_dropfiles = &h233 ‘拖放文件消息
<dllimport("shell32.dll")> public shared sub dragfinish(byval hdrop as integer)
end sub
<dllimport("shell32.dll")> public shared sub dragacceptfiles(byval hwnd as integer, byval faccept as boolean)
end sub
<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
end function
private sub form1_load(byval sender as system.object, byval e as system.eventargs) handles mybase.load
application.addmessagefilter(me)
dragacceptfiles(textbox1.handle.toint32, true)
end sub
function prefiltermessage(byref m as message) as boolean implements imessagefilter.prefiltermessage
if m.msg = wm_dropfiles then
'設(shè)置拖放的動作
dim nfiles as int16
nfiles = dragqueryfile(m.wparam.toint32, -1, nothing, 0)
dim i as int16
dim sb as new system.text.stringbuilder(256)
dim sfirstfilename as string '記錄第一個文件名
textbox1.clear()
for i = 0 to nfiles - 1
dragqueryfile(m.wparam.toint32, i, sb, 256)
if i = 0 then sfirstfilename = sb.tostring
textbox1.appendtext(controlchars.crlf & sb.tostring)
next
dragfinish(m.wparam.toint32) '拖放完成
'顯示文件內(nèi)容
dim fs as new system.io.filestream(sfirstfilename, io.filemode.open)
dim sr as new system.io.streamreader(fs, system.text.encoding.getencoding("gb2312"))
textbox1.appendtext(controlchars.crlf & sr.readtoend().tostring)
fs.close()
sr.close()
end if
return false
end function
protected overloads overrides sub dispose(byval disposing as boolean)
if disposing then
if not (components is nothing) then
components.dispose()
end if
end if
application.removemessagefilter(me)
dragacceptfiles(textbox1.handle.toint32, false)
mybase.dispose(disposing)
end sub
注意:拖放結(jié)束后,調(diào)用dragfinish釋放內(nèi)存。