[英]Drag and drop from windows explorer to custom C# app that actually works with Windows 7
我嘗試(使用幾十個例子)創建一個簡單的WinForms應用程序,它允許我將一個簡單的文本文件拖放到自定義DotNet程序的輸入框中。 不幸的是,似乎沒有實際在Windows 7中運行的示例。
這是一個簡單的例子(來自另一個已經被引用的帖子),但它根本不起作用。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace DragAndDropTestCSharp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.AllowDrop = true;
this.DragEnter += Form1_DragEnter;
this.DragDrop += Form1_DragDrop;
}
private void Form1_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void Form1_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
string[] filePaths = (string[])(e.Data.GetData(DataFormats.FileDrop));
foreach (string fileLoc in filePaths)
{
// Code to read the contents of the text file
if (File.Exists(fileLoc))
{
using (TextReader tr = new StreamReader(fileLoc))
{
MessageBox.Show(tr.ReadToEnd());
}
}
}
}
}
}
}
這可能是UAC問題嗎? 如果是這樣的話,為什么世界上其他所有應用程序似乎都在使用UAC來實現這一簡單而又難以捉摸的拖放功能?
有人有一個真實的,有效的例子,讓它在Windows 7中運行嗎?
我已經嘗試了你的樣品,它工作正常。 檢查是否已將Load事件掛鈎到Form1_Load處理程序的表單對象,並且您的命名空間是相同的。
this.Load += new System.EventHandler(this.Form1_Load);
或通過屬性編輯器:
好吧,我發現在管理員下運行VS(我必須為另一個項目做)是罪魁禍首。 在正常用戶模式下加載VS,它可以在UAC上正常工作。 謝謝大家的投入!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.