I have one windows application in c#, i want to add drag & drop facility in this application, after adding this facility it takes multiple files, so I want to take only one file at a time, how to do this?
read the code below and try applying it to your situation
public Form1()
{
InitializeComponent();
this.AllowDrop = true;
this.DragEnter += Form1_DragEnter;
this.DragDrop += Form1_DragDrop;
}
void Form1_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
e.Effect = DragDropEffects.Copy;
}
void Form1_DragDrop(object sender, DragEventArgs e)
{
var files = (string[])e.Data.GetData(DataFormats.FileDrop);
if (files.Length == 1)
{
// do what you want
}
else
{
// show error
}
}
Related
I have a textbox on a winform in Visual Studio. I want to drag&drop files on it. This is what I have done:
public LangMerge()
{ InitializeComponent();
this.AllowDrop = true;
tbxFilepath.AllowDrop = true;
tbxFilepath.DragDrop += new DragEventHandler(tbxFilepath_DragDrop);
tbxFilepath.DragEnter += new DragEventHandler(tbxFilepath_DragEnter);
}
void tbxFilepath_DragDrop(object sender, DragEventArgs e)
{
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
foreach (string file in files) tbxFilepath.Text=(file);
}
void tbxFilepath_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy;
}
Neither the drag effect nor the receiving of the file does not work. No error messages or warnings. What could be the problem?
UPDATE: I inserted breakpoints into the event handler methods and the code doesn't get into them in the first place, no matter what I do with the cursor.
You have set AllowDrop=true; and handled DragDrop() and DragEnter() events, however for winforms application you need to also handle TextBox.DragOver() event :
Something like this :
private void textBoxFile_DragOver(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
e.Effect = DragDropEffects.Copy;
else
e.Effect = DragDropEffects.None;
}
I'm having trouble loading a file into a RichText control.
First, there are no events in the designer to accomodate drag/drop, so I put these handlers in the form initialization.
Second, the DragEnter() event does not seem to identify text files properly, so dropping is disabled in the RichText (it works fine for a ListBox).
Third, if I get the RT to load the file, it displays an icon/filename inside the RT text area. I cant find any references to this behavior, and can't turn it off.
This code does NOT work:
public Form1()
{
InitializeComponent();
RT.AllowDrop = true;
RT.DragEnter += new System.Windows.Forms.DragEventHandler(RT_DragEnter);
RT.DragDrop += new System.Windows.Forms.DragEventHandler(RT_DragDrop);
}
private void RT_DragEnter(object sender, System.Windows.Forms.DragEventArgs e) {
// when a text file is dragged to this control, GetDataPresent() returns FALSE.
// this seems to be regardless of the file extension. File is ASCII text only.
// this code DOES work if the underlying control is a ListBox.
if (e.Data.GetDataPresent(DataFormats.Text))
e.Effect = DragDropEffects.Move;
else
e.Effect = DragDropEffects.None;
}
private void RT_DragDrop(object sender, System.Windows.Forms.DragEventArgs e) {
string[] filenames = (string[])e.Data.GetData(DataFormats.FileDrop, false);
if (null != filenames){
// when the file is loaded, the RT also displays an icon for the file,
// with the filename, inside the text area ... ?
RT.LoadFile(filenames[0],RichTextBoxStreamType.PlainText);
}
}
In order to get the RT to load a dropped file properly, I use a timer to load the RT outside of the
DragDrop() event:
public string FileToLoad;
private void RT_DragEnter(object sender, System.Windows.Forms.DragEventArgs e) {
// allow anything:
//if (e.Data.GetDataPresent(DataFormats.Text))
e.Effect = DragDropEffects.Move;
//else
//e.Effect = DragDropEffects.None;
}
private void RT_DragDrop(object sender, System.Windows.Forms.DragEventArgs e) {
string[] filenames = (string[])e.Data.GetData(DataFormats.FileDrop, false);
if (null != filenames){
FileToLoad = filenames[0];
timer1.Enabled = true;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
timer1.Enabled = false;
if (FileToLoad.Length > 0)
{
RT.LoadFile(FileToLoad, RichTextBoxStreamType.PlainText);
FileToLoad = "";
}
}
The latter has the RichText loading the file properly, but this seems like a long way around the block to get LoadFile() to work as expected. Am I doing something wrong?
I am writing a little program in C# that scans a folder and opens the files that have been created after 5.30pm after a button has been pressed on the program. This will also have to search within sub-folders.
I need a couple of solutions to point me in the correct direction as I'm not sure how I would do this.
This is part of a folder watcher program. The problem is when the user goes home the PC is switched off and there are files being created to the directory after 17.30. So I need a way for when the program is restarted in the morning it detects anything created after 17.30 and open them.
private void button1_Click(object sender, EventArgs e)
{
folderBrowser.ShowDialog();
textBox1.Text = folderBrowser.SelectedPath;
filewatcher.Path = textBox1.Text;
Registry.SetValue("HKEY_CURRENT_USER\\SOFTWARE\\COMPANY\\FOLDERWATCHER", "FOLDERPATH", textBox1.Text);
}
private void Form1_Load(object sender, EventArgs e)
{
String WatchFolder = Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\COMPANY\\FOLDERWATCHER", "FOLDERPATH", "").ToString();
textBox1.Text = WatchFolder;
filewatcher.Path = WatchFolder;
}
private void Form1_Resize(object sender, EventArgs e)
{
if (WindowState == FormWindowState.Minimized)
{
ShowInTaskbar = true;
Hide();
}
}
private void fileSystemWatcher1_Changed(object sender, System.IO.FileSystemEventArgs e)
{
if(!e.FullPath.EndsWith("temp.temp"))
{
MessageBox.Show("You have a Collection Form: " + e.Name);
Process.Start("explorer.exe", e.FullPath);
}
}
private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
{
Show();
}
}
This is my complete code above. I would like to use a button to open or show the files created after 17.30.
Look at the System.IO namespace, it has everything you need.
the DirectoryInfo and File classes will do what you want.
Here is the recursive method you are looking for:
public static List<string> GetFilesCreatedAfter(string directoryName, DateTime dt)
{
var directory = new DirectoryInfo(directoryName);
if (!directory.Exists)
throw new InvalidOperationException("Directory does not exist : " + directoryName);
var files = new List<string>();
files.AddRange(directory.GetFiles().Where(n => n.CreationTime > dt).Select(n=>n.FullName));
foreach (var subDirectory in Directory.GetDirectories(directoryName))
{
files.AddRange(GetFilesCreatedAfter(subDirectory,dt));
}
return files;
}
Hope I helped.
You can use FileSystemWatcher (MSDN documentation) to detect files that have been created after pressing a button (while your application is running).
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = "C:\\YourDirectory";
watcher.Created += (sender, args) => {
// File was created
}
watcher.EnableRaisingEvents = true;
This allows you to track files as they are created (while your application is running).
If you just want to get a list of all directories that were created in a specified time range (before your application was started), then you can search the directory tree using Directory.GetDirectories and Directory.GetFiles.
In place of datetime place you date and time value.
void DirSearch(string dir)
{
try
{
foreach (string d in Directory.GetDirectories(dir))
{
foreach (string f in Directory.GetFiles(d, "*.*"))
{
if(DateTime.Compare(f.GetCreationTime, datetime))
{
//files found
}
}
DirSearch(d);
}
}
catch (System.Exception excpt)
{
Console.WriteLine(excpt.Message);
}
}
I can't seem to make this work using this:
private void listView1_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
e.Effect = DragDropEffects.Copy;
}
}
private void listView1_DragDrop(object sender, DragEventArgs e)
{
string[] directoryName = (string[])e.Data.GetData(DataFormats.FileDrop);
string[] files = Directory.GetFiles(directoryName[0]);
foreach (string file in files)
{
if (Path.GetExtension(file) == ".mp3")
{
listView1.Items.Add(file);
}
}
}
The mouse cursor shows a NOT sign and I can't drop the folder in my program.
Have you set the AllowDrop property of your ListView to True?
Is your DragEnter event ever being hit?
How do i drag files or folders into a textbox? i want to put the foldername in that very textbox. C# .NET
i wrote this code based in this link
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
textBox1.AllowDrop = true;
textBox1.DragEnter += new DragEventHandler(textBox1_DragEnter);
textBox1.DragDrop += new DragEventHandler(textBox1_DragDrop);
}
private void textBox1_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
e.Effects = DragDropEffects.Copy;
else
e.Effects = DragDropEffects.None;
}
private void textBox1_DragDrop(object sender, DragEventArgs e)
{
string[] FileList = (string[])e.Data.GetData(DataFormats.FileDrop, false);
string s="";
foreach (string File in FileList)
s = s+ " "+ File ;
textBox1.Text = s;
}
}
Set AllowDrop to true on your TextBox, and write the following code for the DragDrop and DragEnter events :
private void textBox1_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
e.Effect = DragDropEffects.Copy;
}
}
private void textBox1_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
string[] fileNames = (string[])e.Data.GetData(DataFormats.FileDrop);
textBox1.Lines = fileNames;
}
}
CodeProject has a really nice example of doing this, including how to enable drag and drop both ways (from Explorer to your app, and from your app to Explorer).
Control has various events for dealing with drag/drop - you'll probably only need to look at the DragDrop event for what you want.
If you get the Error Messages below, This applied to me when using Visual Studio 2015, try
e.Effect instead of e.Effects
Severity Code Description Project File Line Suppression State
Error CS1061 'DragEventArgs' does not contain a definition for 'Effects' and no extension method 'Effects' accepting a first argument of type 'DragEventArgs' could be found (are you missing a using directive or an assembly reference?)