Trying to create Drag and Drop with PictureBoxes - events don't trigger - c#

EDIT 1/Resolution:
Okay I found what was missing. I did not set any event handlers.
Now it works with the following
public Form1()
{
InitializeComponent();
pictureBox1.DragEnter += new DragEventHandler(pictureBox1_DragEnter);
pictureBox1.DragDrop += new DragEventHandler(pictureBox1_DragDrop);
}
So my next question would be....why do I have to set these? Something like a ButtonClick knows exactly where to go...so why wouldn't these other events?
I'm still a little new to C#.
-
ORIGINAL QUESTION:
I'm messing around with dragging and dropping images into a picturebox from my computer.
I have a working version of this in VB. So I just translated (as best I could) it all into C#.
My DragEnter event isn't even triggering at all...I'm not sure what I am missing.
I had to change some things because of the C#/VB differences, but it's basically the same code. I feel like I am missing more events or something...I just don't know what.
Even if it does turn out I have some code wrong...my program never even fires DragEnter....if I put a dummy Debug line or MessageBox in that event just to see if it ran.....it never does.
My form load
private void Form1_Load(object sender, EventArgs e)
{
pictureBox1.AllowDrop = true;
pictureBox1.BorderStyle = BorderStyle.FixedSingle;
this.AllowDrop = true;
}
My DragEnter
private void pictureBox1_DragEnter(object sender, DragEventArgs e)
{
string[] formats = e.Data.GetFormats();
if (e.Data.GetDataPresent(DataFormats.Bitmap))
{
if (e.KeyState == CtrlMask && CtrlMask == CtrlMask)
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.Move;
}
}
else if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
e.Effect = DragDropEffects.All;
}
else if (e.Data.GetDataPresent(DataFormats.Rtf))
{
if (e.KeyState == CtrlMask && CtrlMask == CtrlMask)
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.Move;
}
}
}
And my DragDrop..
private void pictureBox1_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.Bitmap))
{
var bmp = (Bitmap)e.Data.GetData(DataFormats.Bitmap);
pictureBox1.Image = bmp;
}
else if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
string[] files;
files = (string[])e.Data.GetData(DataFormats.FileDrop);
foreach (string file in files)
{
string Newfile = file.ToLower();
string[] ImageTypes = { "gif", "jpg", "png", "bmp" };
string ActualFileExt = "";
foreach (string FileExtension in ImageTypes)
{
if (Newfile.EndsWith(FileExtension))
{
ActualFileExt = FileExtension;
}
}
if (ActualFileExt != "")
{
pictureBox1.Image = new Bitmap(Newfile);
}
}
}
else if (e.Data.GetDataPresent(DataFormats.Rtf))
{
}
}

You had to explicitly add the handlers since you did not use the 'Handles' keyword after your drop/enter methods. Notice the example code in this example uses the Handles keyword similar to a button.

Related

Windows Forms C# (DragDrop for 100 objects)

I have currently a question for my school-project (we want to develop a Block Puzzle like game).
We build a field (10x10)
I already got to manage the DragDrop for "my field1x1".
private void field1x1_DragDrop(object sender, DragEventArgs e)
{
fieldBoxes[0,0].Image = (Bitmap)e.Data.GetData(DataFormats.Bitmap, true);
}
foreach (PictureBox checks in fieldBoxes)
{
checks.AllowDrop = true;
checks.DragEnter += field1x1_DragEnter;
checks.DragDrop += field1x1_DragDrop;
}
and my question is : how can i simplify the code that i don't have to create 100 DragDrops manually?
because
private void field1x1_DragDrop(object sender, DragEventArgs e)
{
if (sender is PictureBox)
{
((PictureBox)sender).Image = (Bitmap)e.Data.GetData(DataFormats.Bitmap, true);
}
}
This was the solution

C# Drag and Drop text within a RichTextBox

I have a C# project in which I want the user to be able to drag and drop text (i.e. to move text) within a RichTextBox in a WinForm.
I have found many examples showing how to do drop something onto a RichTextBox but I didn't succeed to have them work when the RichTextBox is both the drag source and drop target.
How should I do this ?
Below is my non-working attempt sofar.
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
this.richTextBox1.AllowDrop = true;
this.richTextBox1.DragEnter += new System.Windows.Forms.DragEventHandler(this.richTextBox1_DragEnter);
this.richTextBox1.DragDrop += new System.Windows.Forms.DragEventHandler(this.richTextBox1_DragDrop);
}
private void richTextBox1_DragEnter(object sender, System.Windows.Forms.DragEventArgs e) {
if (e.Data.GetDataPresent(DataFormats.Rtf))
e.Effect = DragDropEffects.Move;
else
e.Effect = DragDropEffects.None;
}
private void richTextBox1_DragDrop(object sender, System.Windows.Forms.DragEventArgs e) {
int i;
String s;
i = richTextBox1.SelectionStart;
s = richTextBox1.Text.Substring(i);
richTextBox1.Text = richTextBox1.Text.Substring(0, i);
richTextBox1.Text = richTextBox1.Text +
e.Data.GetData(DataFormats.Text).ToString();
richTextBox1.Text = richTextBox1.Text + s;
}
}
Well, I found myself a solution to this problem :
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
richTextBox1.EnableAutoDragDrop = true;
}
}
And nothing more.
My first attempt was based on MSDN documentation:
http://msdn.microsoft.com/en-us/library/aa984395(v=vs.71).aspx, but it seems broken.
Drag and drop text within RXBox (RichTextBox):
Run HookOn_EventHandlers_etc() during Initialize(). Dragging mouse will fire the DragEnter and DragDrop events. In RXBox_DragDrop(), set DragDropEffects back to None.
private void HookOnEventHandlers_etc()
{
RXBox.DragEnter += RXBox_DragEnter;
RXBox.DragDrop += RXBox_DragDrop;
RXBox.AllowDrop = true;
RXBox.EnableAutoDragDrop = true;
}
private void RXBox_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.Text))
e.Effect = DragDropEffects.Copy;
else
e.Effect = DragDropEffects.None;
}
private void RXBox_DragDrop(object sender, DragEventArgs e)
{
RXBox.SelectedText = e.Data.GetData(DataFormats.Text).ToString();
e.Effect = DragDropEffects.None; // with this the paste won't be doubled
}

Button Background Image Check?

Pls i have a problem with trying to check the background Image of a button. I want to delete the button if its image matches an Image in the Resource Folder. I have Tried
private void DeleteCard(Button btn)
{
if (btn.BackgroundImage.Equals( FunWaysInc.Properties.Resources.Card_1))
{
playersCards.Remove(Properties.Resources.Card_1);
MessageBox.Show(playersCards.Count.ToString());
}
else
{
MessageBox.Show("NO");
}
}
private void frmQuickSpark_Load(object sender, EventArgs e)
{
Button tstbtn = new Button();
tstbtn.BackgroundImage = Properties.Resources.Card_1;
DeleteCard(tstbtn);
}
but the message box displayed is the one that displays "NO"..
Pls what is happening????
when adding the button
button.Tag = "ToDelete";
then later
foreach (Button b in this.Controls.OfType<Button>())
{
if(b.Tag == "ToDelete")
{
//delete
}
}
Here what you have to do. You need to enumerate all your images and store pointer in Tag property of the button.
private Dictionary<string, Image> _table = new Dictionary<string, Image>();
private void frmQuickSpark_Load(object sender, EventArgs e)
{
_table.Add("Image1", Properties.Resources.Card_1);
_table.Add("Image2", Properties.Resources.Card_2);
Button btn = new Button();
SetButtonImage(btn);
DeleteCard(btn);
}
private void SetButtonImage(Button button)
{
button.BackgroundImage = _table["Image1"];
button.BackgroundImage.Tag = "Image1";
}
private void DeleteCard(Button btn)
{
if (btn.BackgroundImage.Tag == "Image1")
{
playersCards.Remove(btn); // not sure what your logic of removal
MessageBox.Show(playersCards.Count.ToString());
}
else
{
MessageBox.Show("NO");
}
}
I already found an answer to my question.. I just modified my code
private void DeleteCard(Image img)
{
playersCards.Add(Properties.Resources.Card_1);
if (img == playersCards[0])
{
playersCards.Remove(Properties.Resources.Card_1);
MessageBox.Show(playersCards.Count.ToString());
}
else
{
MessageBox.Show("NO");
}
}
private void frmQuickSpark_Load(object sender, EventArgs e)
{
Button tstbtn = new Button();
tstbtn.BackgroundImage = Properties.Resources.Card_1;
Image img = tstbtn.BackgroundImage;
DeleteCard(img);
}
It works perfectly.

Display dropped image on Form

I have a C# app and i want it that when an Image is dropped on the form, A picturebox in the form displays the Image. I have tried this
private void Form1_DragEnter(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Move;
}
private void Form1_DragDrop(object sender, DragEventArgs e)
{
Graphics p = pictureBox1.CreateGraphics();
p.DrawImage((Image)e.Data.GetData(DataFormats.Bitmap), new Point(0, 10));
}
But it doesn't work.
Pls what did i do wrong?
I think you are dragging from file.
Simple code for this will be such:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.AllowDrop = true;
this.DragDrop += new System.Windows.Forms.DragEventHandler(this.Form1_DragDrop);
this.DragEnter += new System.Windows.Forms.DragEventHandler(this.Form1_DragEnter);
}
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)
{
string[] filex = (string[])e.Data.GetData(DataFormats.FileDrop);
if (filex.Length > 0)
{
pictureBox1.ImageLocation = filex[0];
}
}
}
i truly hope this is not the solution but you didn't gave much information so i'll start here and we'll go as you give us more information.
when you toke this sample did you bind it to the proper events?
as in:
this.DragDrop += new System.Windows.Forms.DragEventHandler(this.Form1_DragDrop);
this.DragEnter += new System.Windows.Forms.DragEventHandler(this.Form1_DragEnter);
also, on initializing, did you do:
AllowDrop = true;

Change the mouse drag cursor in WPF

I have to disply the number of dragged files count on mouse cursor while dragging document from file system to my form.
I have done the following code, but I can not change the drag cursor. Please let me know the best way to do this
private void tbDisplayFileContents_PreviewDragOver(object sender, DragEventArgs args)
{
if (IsSingleFile(args) != null)
{
tbDisplayFileContents_PreviewDrop(sender, args);
}
else
{
// args.Effects = DragDropEffects.None;
}
Mouse.SetCursor(Cursors.Hand);
Icon ico = new Icon(string.Concat("1365516094_10371.ico"));
tbDisplayFileContents.Cursor = GenerateCursor.CreateCursor(ico, true, new System.Drawing.Color());
args.Handled = true;
}
private void tbDisplayFileContents_PreviewDrop(object sender, DragEventArgs args)
{
args.Handled = true;
string files = string.Empty;
string[] fileName = IsSingleFile(args);
if (fileName == null) return;
isDrag = true;
DoEvents();
for (int i = 0; i < fileName.Length; i++)
{
if (i == 0)
{
files = string.Concat("1] ", fileName[i]);
}
else
{
int j = i + 1;
files = string.Concat(files, Environment.NewLine, j, "] ", fileName[i]);
}
}
lblfileName.Content = files;
}
private string[] IsSingleFile(DragEventArgs args)
{
if (args.Data.GetDataPresent(DataFormats.FileDrop, true))
{
string[] fileNames = args.Data.GetData(DataFormats.FileDrop, true) as string[];
if (fileNames.Length != 0)
{
if (File.Exists(fileNames[0]))
{
// At this point we know there is a single file.
return fileNames;
}
}
}
return null;
}
#endregion
#region -------Events--------
private void btnClear_Click(object sender, RoutedEventArgs e)
{
lblfileName.Content = string.Empty;
}
#endregion
private void tbDisplayFileContents_PreviewDragEnter(object sender, DragEventArgs e)
{
e.Effects = DragDropEffects.None;
}
public static void DoEvents()
{
Application.Current.Dispatcher.Invoke(DispatcherPriority.Background,
new Action(delegate
{
Icon ico = new Icon(string.Concat("1365516094_10371.ico"));
Mouse.OverrideCursor = GenerateCursor.CreateCursor(ico, true, new System.Drawing.Color());
}));
}
I have used GiveFeedBack event as follows
private void tbDisplayFileContents_GiveFeedback(object sender, GiveFeedbackEventArgs e)
{
if (e.Effects == DragDropEffects.Copy)
{
e.UseDefaultCursors = false;
// Mouse.SetCursor(Cursors.Hand);
Icon ico = new Icon(string.Concat("1365516094_10371.ico"));
//Mouse.Cursor = GenerateCursor.CreateCursor(ico, true, new System.Drawing.Color());
Mouse.SetCursor(GenerateCursor.CreateCursor(ico, true, new System.Drawing.Color()));
}
else
e.UseDefaultCursors = true;
e.Handled = true;
}
It is working for form to form dragging but it is not working for the contents(file) which is dragged from outside form e.g files from Desktop.
I miss the GiveFeedback event in your code, which is used to modify the Mouse cursor while drag and drop operations.

Categories

Resources