zoukankan      html  css  js  c++  java
  • C#,visual studio 2010中实现最简单DragDrop实例

    问题:将一个文件拖放到文本框中,并在文本框中显示这个文件的名字

    第一步,需要将文本框的AllowDrop属性设置为true,或者在Form里面手动设置,从英文字面翻译为允许拖放,设置为false自然是不允许拖放

    本文文本框的ID为:txt对应图像

    public Form1()
            {
                InitializeComponent();
                this.txt对应图像.AllowDrop = true;
            }
    

    image

    第二步,设置好这个文本框的两个事件,

    image

    private void 拖放图像完成时(object sender, DragEventArgs e)
            {
                //从拖放的事件中取得需要的数据,注意要转换成字符串数组
                //然后再从字符串数组中取值
                var filename = (string[])e.Data.GetData(DataFormats.FileDrop);
                txt对应图像.Text = filename[0];
            }
    
    private void 拖放图像进入时(object sender, DragEventArgs e)
            {
                // 确定拖放的是文档
                if (e.Data.GetDataPresent(DataFormats.FileDrop, false) == true)
                {
                    // 允许拖放动作继续,此时鼠标会显示为+
                    e.Effect = DragDropEffects.All;
                }
            }
    第三步:测试,将一个文本文件拖放到文本框上,松开后这个文件名字就放到了文本框中.
    image
    下面是从网上找到的例子,我的方法就是从这儿学来的.
     

    最簡單範例

    準備工作
    1. 建立一個 Form, 並且拉一個 listBox 元件到上面
    2. 命名 listBox 為 listBox_FileList

    執行步驟
    // Step 1: 拖拉功能啟動
    this.listBox_FileList.AllowDrop = true;

    // Step 2: 在 listBox_FileList 的 DragEnter 事件中, 加入下面程式碼
    private void listBox_FileList_DragEnter(object sender, DragEventArgs e)
    {
    // 確定使用者抓進來的是檔案
    if (e.Data.GetDataPresent(DataFormats.FileDrop, false) == true)
    {
    // 允許拖拉動作繼續 (這時滑鼠游標應該會顯示 +)
    e.Effect = DragDropEffects.All;
    }
    }

    // Step 3: 在 listBox_FileList 的 DragDrop 事件中, 加入下面程式碼
    private void listBox_FileList_DragDrop(object sender, DragEventArgs e)
    {
    string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
    foreach (string file in files)
    {
    listBox_FileList.Items.Add(file);
    }
    }

    完成 !!

  • 相关阅读:
    iOS开发之直接使用UISearchBar
    iOS开发之cell多按钮
    Cocoapods报错xcrun: error: active developer path ("/Users/wangwei/Downloads/Xcode.app/Contents/Developer") does not exist
    lyl
    最全ASCLL码
    在子线程中使用runloop,正确操作NSTimer计时的注意点 三种可选方法
    ANSI escape code
    cocoa
    boundingRectWithSize:options:attributes:context:
    iOS 9 storyboard自动布局
  • 原文地址:https://www.cnblogs.com/angestudy/p/2002901.html
Copyright © 2011-2022 走看看