I have seen this everywhere and tried all the solutions and am not seeming to get what I want. I want to be able to drop files from explorer onto a ListView and then be able to sort them through drag and drop. I am have this simple code that gets the drag/drop from explorer.
this.messageView.AllowDrop = true;
this.messageView.Location = new System.Drawing.Point(12, 52);
this.messageView.Name = "messageGrid";
this.messageView.Size = new System.Drawing.Size(121, 97);
this.messageView.TabIndex = 3;
this.messageView.UseCompatibleStateImageBehavior = false;
this.messageView.DragDrop += new System.Windows.Forms.DragEventHandler(this.Form1_DragDrop);
this.messageView.DragEnter += new System.Windows.Forms.DragEventHandler(this.Form1_DragEnter);
and the handlers
private void Form1_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent("FileGroupDescriptor"))
{
e.Effect = DragDropEffects.All;
}
}
private void Form1_DragDrop(object sender, DragEventArgs e)
{
messageView.Items.Add(e.Data.ToString());
}
This is bizarre, because of I change the messageView to a RichTextBox I have on my form, it works just fine. Are there additional steps that I have to do? When I attempt to drop onto the ListView, I get the circle with a line through it from Explorer. Any help would be appreciated. Thanks.
DragEnter and DragDrop events should be handled in the ListView, not in the Form.
About drag and drop: I do not remember the article name but I found a good example of it in codeproject.
Related
As described in the title, I have a Form with a Datagridview on the front. The datagridview is smaller than my form in the back and I want the Datagridview to disappear whenever I click anywhere else but the Datagridview.
My code looks like this:
this.dataGridView1.Leave += new System.EventHandler(this.focus);
and the Eventhandler is defined like this:
private void focus(object sender, EventArgs e)
{
if(dataGridView1.Focused == false)
{
dataGridView1.Visible = false;
}
}
My problem is that my Datagridview only disappears when a new event in my form is activated but not when I click for example in a textbox on my form.
Can anyone help me?
The Leave event will not raise if you click on Form, or a ToolStripButton, PictureBox or any other non-selectable control.
If you expect a behavior like a dropdown, you can host DataGridView in a ToolStripControlHost and show it using a ToolStripDropDown. This way when you click anywhere outside the `DataGridView, it will disappear. It will act like a dropdown menu. Also the grid can be larger than your form:
private void button1_Click(object sender, EventArgs e)
{
this.dataGridView1.Margin = new Padding(0);
var host = new ToolStripControlHost(this.dataGridView1);
this.dataGridView1.MinimumSize = new Size(200, 100);
host.Padding = new Padding(0);
var dropdown = new ToolStripDropDown();
dropdown.Padding = new Padding(0);
dropdown.Items.Add(host);
dropdown.Show(button1, 0,button1.Height);
}
Important Note: It's an example. It's better to pay attention to disposing of objects in a real world application. For example, use just a single ToolStripdropDown and dispose it when closing the form.
Change the event handler assigning to:
this.dataGridView1.Leave += new System.EventHandler(fokussiert);
Worked for me when focusing on a textbox
you want your dgv also to disapear when you click on your textbox? is that what you mean?
private void dataGridView1_Leave(object sender, EventArgs e)
{
dataGridView1.Visible = false;
}
private void Form1_Click(object sender, EventArgs e)
{
dataGridView1.Visible = false;
}
I have a ListBox with a list of filepaths, which has the property SelectionMode set to MultiExtended. Thus, I can select many items from this list.
Now, I want to Drag and Drop files starting from those paths in the destination folder where I drop them.
My code:
private void Form1_Load(object sender, EventArgs e)
{
// populate the FileList
// i.e. FileList.Items.Add("d:/Samples/file-00" + i + ".wav");
this.FileList.MouseDown += new MouseEventHandler(FileList_MouseDown);
this.FileList.DragOver += new DragEventHandler(FileList_DragOver);
}
void FileList_DragOver(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Copy;
}
void FileList_MouseDown(object sender, MouseEventArgs e)
{
List<string> filesToDrag = new List<string>();
foreach (var item in FileList.SelectedItems)
{
filesToDrag.Add(item.ToString().Trim());
}
this.FileList.DoDragDrop(new DataObject(DataFormats.FileDrop,
filesToDrag.ToArray()), DragDropEffects.Copy);
}
it works perfect if I select and drop 1 single line/file from the ListBox to the destination folder.
Instead, if I do a multiple selection and I try to drag and drop, it can just select that one line where I start to drag. Seems that MouseDown prevent this?
How would you fix the problem?
Doing this with a ListBox seems to be ridiculously hard. Actually I haven't found a solution at all..
Use a ListView instead! It is easy as pie, using the ItemDrag event and is a much better control anyway.. I can't count how often I had to change from a 'cheap' ListBox to ListView because I needed this or that 'little' extra..
Here is your code moved to a ItemDrag:
private void listView1_ItemDrag(object sender, ItemDragEventArgs e)
{
List<string> filesToDrag = new List<string>();
foreach (var item in listView1.SelectedItems)
{
filesToDrag.Add(item.ToString().Trim());
}
this.listView1.DoDragDrop(new DataObject(DataFormats.FileDrop,
filesToDrag.ToArray()), DragDropEffects.Copy);
}
Note that this only solves the problem of the MouseDown changing the selection. It is in itself not a guarantuee that the actual copying will work.
I found this interesting article that proposes a solution. Maybe you don't need it, as you have said that you got copying one file already working..
Yeah...I don't think there's a good way around that problem. When you click again to initiate the drag it will toggle that item. We don't know that the user actually wants to do a drag until the mouse is held down and moved.
One potential solution is to initiate the drag/drop from something else, just somehow make it really clear that is what the user should drag. Here I'm using a Label instead of the ListBox:
void label1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Left)
{
List<string> filesToDrag = new List<string>();
foreach (var item in FileList.SelectedItems)
{
filesToDrag.Add(item.ToString().Trim());
}
if (filesToDrag.Count > 0)
{
this.FileList.DoDragDrop(new DataObject(DataFormats.FileDrop,
filesToDrag.ToArray()), DragDropEffects.Copy);
}
else
{
MessageBox.Show("Select Files First!");
}
}
}
You have to be picky about the mouse down and mouse move activities. When it is within the graphics rectangle of your listbox, you'll want normal behavior. When it is outside the bounds of this rectangle, you'll want drag/drop functionality. You can try the pseudo code below:
MouseDown(sender, e)
{
var x = <your sender as control>.ItemFromPoint(.....)
this.mouseLocation = x == null ? x : e.Location;
}
MouseMove(sender, e)
{
if control rectangle doesn't contain the current location then
<your sender as control>.Capture = false
DoDragDrop
}
I am trying to move some controls around on a WinForm with the mouse. I am using the code below. To see my issue start a new project in VS add the code below. Set the form BackGroundImage to any image then add any control. Set the control events for MouseUp, MouseDown, and MouseMove. Start debugging and click and move the control. The image in the form starts getting erased. I have tried several different suspend drawing classes and methods I have found on the net but nothing I have found lets me move the controls around without serious flickering or not being able to see the move. Any help would be appreciated.
P.S. If you set the same events to the up, move, and down events of the form, it moves fine with out any flickering.
private bool _mouseDown;
private Point _startPoint;
private void Event_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
_mouseDown = true;
_startPoint = new Point(e.X, e.Y);
}
}
private void Event_MouseUp(object sender, MouseEventArgs e)
{
_mouseDown = false;
}
private void Event_MouseMove(object sender, MouseEventArgs e)
{
if (_mouseDown)
{
Control s = sender as Control;
s.Location = new Point(e.X + s.Left - _startPoint.X, e.Y + s.Top - _startPoint.Y);
}
}
Forgive the rather poor code here.
I have a picture box PictureBox and a section Panel. I am trying to start a drag and drop operation so you click and drag the picture box, and dropping it into the Section creates a copy. This is fine.
But the problem is, lets say you click the picture box 9 times, no drag, just clicks. Then on the 10th turn, you do a correct drag and drop operation.... Then you get 10 duplicates added to the Section.
I am guessing that I need to respond to when a DragAndDrop is invalid and stop the drag and drop operation to prevent these duplicate buildups, but I do not know where to look to achieve this.
private void collectablePictureBox_MouseDown(object sender, MouseEventArgs e)
{
this.SelectedSection.AllowDrop = true;
this.SelectedSection.DragEnter += new DragEventHandler(this.CollectableSelectedSection_DragEnter);
this.SelectedSection.DragDrop += new DragEventHandler(this.CollectableSelectedSection_DragDrop);
this.collectablePictureBox.DoDragDrop(this.SelectedClassModel, DragDropEffects.Copy);
}
private void CollectablePictureBox_QueryContinueDrag(object sender, QueryContinueDragEventArgs e)
{
Console.WriteLine(e.Action);
}
private void CollectableSelectedSection_DragEnter(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Copy;
}
private void CollectableSelectedSection_DragDrop(object sender, DragEventArgs e)
{
Point position = this.SelectedSection.PointToClient(new Point(e.X, e.Y));
position.X -= this.SelectedClassModel.Width >> 1;
position.Y -= this.SelectedClassModel.Height >> 1;
this.SelectedSection.AllowDrop = false;
this.SelectedSection.DragEnter -= this.CollectableSelectedSection_DragEnter;
this.SelectedSection.DragDrop -= this.CollectableSelectedSection_DragDrop;
this.SelectedSection.AddItem(this.SelectedClassModel, position, this.SectionCanvasSnapToGridCheckBox.Checked);
}
Your problem comes from the fact that on every MouseDown event you add handlers to the appropriate events, so when you actually do the Drag and Drop those handlers will be called more than once. Currently I see two different ways of solving this:
One way to solve the problem would be to not start the Drag and Drop on the MouseDown event handler, but - based on this MSDN article - start it in a MouseMove handler instead, like this:
private void collectablePictureBox_MouseMove(object sender, MouseEventArgs e)
{
if (sender != null && e.LeftButton == MouseButtonState.Pressed)
{
this.SelectedSection.AllowDrop = true;
this.SelectedSection.DragEnter += new DragEventHandler(this.CollectableSelectedSection_DragEnter);
this.SelectedSection.DragDrop += new DragEventHandler(this.CollectableSelectedSection_DragDrop);
this.collectablePictureBox.DoDragDrop(this.SelectedClassModel, DragDropEffects.Copy);
}
}
Another way would be to also handle the MouseUp event of the PictureBox, and do a similar cleanup as in your CollectableSelectedSection_DragDrop handler.
A good morning to you all!
Yesterday I ran into a problem while trying to implement a custom DragDrop for my own controls in a WinForms application.
I have a form which can dynamically create instances of two of my own controls. These controls consist of some controls themselves, such as buttons, labels and listboxes/treeviews. The controls serve as a representation for a certain dataset. Now, we all know the class diagrams in VS. There you have these boxes representing classes. You can move the boxes around on the canvas by doing - what I would call - dragging them around, much like you would drag around files. To accomplish this with my own controls I have done the following:
public partial class MyControl: UserControl
{
private Control activeControl;
private void GeneralMouseDown(MouseEventArgs e)
{
activeControl = this;
previousLocation = e.Location;
Cursor = Cursors.Hand;
}
private void GeneralMouseMove(Control sender, MouseEventArgs e)
{
if (activeControl == null || activeControl != sender)
return;
var location = activeControl.Location;
location.Offset(e.Location.X - previousLocation.X, e.Location.Y - previousLocation.Y);
activeControl.Location = location;
}
private void GeneralMouseUp()
{
activeControl = null;
Cursor = Cursors.Default;
}
}
The controls on my control which I want to "grab" for dragging MyControl have their MouseDown-, MouseMove- and MouseUp-events pointing to these three methods. As a result I can move my control about on the form freely, just as I want to.
Here comes the tricky bit:
The datasets I have controls for can be in hierarchical dependencies, which means, one control represents detailling of a component of the other, which is why my controls have Listboxes or TreeViews. To establish such a hierarchical dependency I would very much like to DragDrop the lower-order-control on the listbox of my higher-order-control, causing data to be transfered.
I know how to set up my DragEnter and DragDrop methods for the listbox, as I have done so previously with files. Just for completeness:
private void lst_MyControl_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(MyControl)))
e.Effect = DragDropEffects.Move;
else e.Effect = DragDropEffects.None;
}
Here's the problem: As I am moving my control about (which gets repainted at every position, giving a very much wanted effect!), when I "drag" it over the target-listbox, the DragEnter-event does not get fired. I thought I could work around this problem by telling Windows "Hey, I'm, Dragging'n'Dropping here!", thus adding to my GeneralMouseDown-method:
this.DoDragDrop(this, DragDropEffects.Move);
This, on the one hand, gets the DragEnter-event to fire => Yeah! On the other hand is the moving-around-part only working after I release the mouse, causing the control to hang on the mousepointer forever => Anti-Yeah!
Here's the question: Is there a way, to have both actions at the same time? So that I can move my control around, seing it at every position as I do now and fire the DragEnter-event when I get to that area of the other control?
Moving your Control around interferes with the automatic DragDrop handling.
I'd recommend to staying with the normal DragDrop procedures, that is leaving all visuals to the system: It will display a cursor that indicates when a valid target is entered, then change to one that indicates the operation.
You need just 3 lines, no hassle and the user won't seen bulky controls moving around.
Here is a version where I drag a PictureBox onto a ListBox:
private void listBox1_DragEnter(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Copy;
}
private void listBox1_DragDrop(object sender, DragEventArgs e)
{
listBox1.Items.Add( e.Data.GetData(DataFormats.Text));
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Left)
pictureBox1.DoDragDrop(pictureBox1.ImageLocation, DragDropEffects.Copy);
}
Obviously you will set up and receive your data in your own ways..
Edit:
Now, if on the other hand you need to move controls around to rearrange them, maybe you should give up on Drag&Drop to handle the additional data transfers and code this portion on your own as well. You could use the MouseEnter event of a receiving control..
After a bit of fiddeling I did it. I switched the level on which the dragging is handled.
First I need just the MouseDown-event
public Point GrabPoint;
private void GeneralMouseDown(MouseEventArgs e)
{
GrabPoint = e.Location;
this.DoDragDrop(this, DragDropEffects.Move);
}
I set the point where I grab the control and initiate a DragDrop. On my form I handle all the dragging:
private void frmMain_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(MyControl1)) || e.Data.GetDataPresent(typeof(MyControl2)) || e.Data.GetDataPresent(typeof(MyControl3)))
e.Effect = DragDropEffects.Move;
else e.Effect = DragDropEffects.None;
}
private void frmMain_DragOver(object sender, DragEventArgs e)
{
Point DragTarget = new Point(e.X, e.Y);
Point GrabPoint = new Point(0, 0);
if (e.Data.GetDataPresent(typeof(MyControl1)))
GrabPoint = ((MyControl1)e.Data.GetData(typeof(MyControl1))).GrabPoint;
else if (e.Data.GetDataPresent(typeof(MyControl2)))
GrabPoint = ((MyControl2)e.Data.GetData(typeof(MyControl2))).GrabPoint;
else if (e.Data.GetDataPresent(typeof(MyControl3)))
GrabPoint = ((MyControl3)e.Data.GetData(typeof(MyControl3))).GrabPoint;
DragTarget.X -= GrabPoint.X;
DragTarget.Y -= GrabPoint.Y;
DragTarget = this.PointToClient(DragTarget);
if (e.Data.GetDataPresent(typeof(MyControl1)))
((MyControl1)e.Data.GetData(typeof(MyControl1))).Location = DragTarget;
else if (e.Data.GetDataPresent(typeof(MyControl2)))
((MyControl2)e.Data.GetData(typeof(MyControl2))).Location = DragTarget;
else if (e.Data.GetDataPresent(typeof(MyControl3)))
((MyControl3)e.Data.GetData(typeof(MyControl3))).Location = DragTarget;
}
At the moment I don't need the DragDrop-event, since nothing should happen when any control is dropped on the form. This way I always paint my control while it is being dragged => Yeah!
The next part is easy: Since I am really dragging the control, this bit of code does DragDrop-handling on my listbox Edit: ListView:
private void lst_SubControls_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(MyControl2)))
e.Effect = DragDropEffects.Move;
else e.Effect = DragDropEffects.None;
}
private void lst_SubControls_DragDrop(object sender, DragEventArgs e)
{
lst_SubControls.Items.Add(((MyControl2)e.Data.GetData(typeof(MyControl2))).SpecificDrive);
((MyControl2)e.Data.GetData(typeof(MyControl2))).DeleteThisControl();
}
This results in an entry added to the list and deletion of the dragged control. At this point there could be a check, wether the ctrl-key is pressed to copy the contents and not to delete the control.