最近做了一個小工具,在winform中對picture控件有一個需求,可以通過鼠標從外部拖拽圖片到控件的上,釋放鼠標,顯示圖片!
首先你需要對你的整個fom窗口的allowdrop設置ture
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
//函數從動態鏈接庫中倒入(模擬鼠標事件) [system.runtime.interopservices.dllimport( "user32" )] private static extern int mouse_event( int dwflags, int dx, int dy, int cbuttons, int dwextrainfo); const int mouseeventf_leftdown = 0x0002; //模擬鼠標左鍵按下 const int mouseeventf_leftup = 0x0004; //模擬鼠標左鍵抬起 //設置靜態字段傳遞圖片路徑參數 public static string path_url; //獲取鼠標拖入圖片的絕對路徑 private void form1_dragdrop( object sender, drageventargs e) { //獲取當前推拽圖片的路徑 string path1 = ((system.array)e.data.getdata(dataformats.filedrop)).getvalue(0).tostring(); ; path_url = path1; //模擬鼠標釋放鼠標左鍵的時事件 mouse_event(mouseeventf_leftup | mouseeventf_leftup, cursor.position.x, cursor.position.y, 0, 0); } //判斷鼠標拖入文件的類型判斷是不是文件類型 private void form1_dragenter( object sender, drageventargs e) { if (e.data.getdatapresent(dataformats.filedrop)) //需求有一需要從qq的聊天記錄中拖拽圖片到winform窗體中,用all會出現qq的聊天信息中的圖片丟失 //link和move不能從qq的聊天記錄中拖拽圖片到winform窗體中,copy和scroll都可以實現,推薦使用copy e.effect = dragdropeffects.copy; else e.effect = dragdropeffects.none; } |
在來設置picturebox的事件
1
2
3
4
5
6
|
//當鼠標在當前控釋放的時候觸發控件 private void pic_1_mouseup( object sender, mouseeventargs e) { //給picturebox設置圖片路徑 pic_1.imagelocation = path_url; } |
以上就可以完成推拽圖片顯示圖片(無論是本地還是qq消息框中的圖片都可以實現)
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://www.cnblogs.com/2828sea/archive/2018/09/20/9682937.html