软件编程
位置:首页>> 软件编程>> C#编程>> Winform控件Picture实现图片拖拽显示效果

Winform控件Picture实现图片拖拽显示效果

作者:喜欢吃鱼的青年  发布时间:2022-04-01 05:49:54 

标签:winform,Picture,图片拖拽

最近做了一个小工具,在Winform中对Picture控件有一个需求,可以通过鼠标从外部拖拽图片到控件的上,释放鼠标,显示图片!

Winform控件Picture实现图片拖拽显示效果

首先你需要对你的整个Fom窗口的AllowDrop设置Ture

Winform控件Picture实现图片拖拽显示效果


//函数从动态链接库中倒入(模拟鼠标事件)

[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;
}

Winform控件Picture实现图片拖拽显示效果

在来设置PictureBox的事件

Winform控件Picture实现图片拖拽显示效果


//当鼠标在当前控释放的时候触发控件
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

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com