C# Drag & Drop Multiple Images within Canvas - c#

I've got the following code to drag and drop images inside my Canvas:
img.AllowDrop = true;
img.PreviewMouseLeftButtonDown += this.MouseLeftButtonDown;
img.PreviewMouseMove += this.MouseMove;
img.PreviewMouseLeftButtonUp += this.PreviewMouseLeftButtonUp;
private object movingObject;
private double firstXPos, firstYPos;
private void MouseLeftButtonDown(object sender, MouseButtonEventArgs e) {
// In this event, we get the current mouse position on the control to use it in the MouseMove event.
Image img = sender as Image;
Canvas canvas = img.Parent as Canvas;
firstXPos = e.GetPosition(img).X;
firstYPos = e.GetPosition(img).Y;
movingObject = sender;
// Put the image currently being dragged on top of the others
int top = Canvas.GetZIndex(img);
foreach (Image child in canvas.Children)
if (top < Canvas.GetZIndex(child))
top = Canvas.GetZIndex(child);
Canvas.SetZIndex(img, top + 1);
}
private void PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e) {
Image img = sender as Image;
Canvas canvas = img.Parent as Canvas;
movingObject = null;
// Put the image currently being dragged on top of the others
int top = Canvas.GetZIndex(img);
foreach (Image child in canvas.Children)
if (top > Canvas.GetZIndex(child))
top = Canvas.GetZIndex(child);
Canvas.SetZIndex(img, top + 1);
}
private void MouseMove(object sender, MouseEventArgs e) {
if (e.LeftButton == MouseButtonState.Pressed && sender == movingObject) {
Image img = sender as Image;
Canvas canvas = img.Parent as Canvas;
double newLeft = e.GetPosition(canvas).X - firstXPos - canvas.Margin.Left;
// newLeft inside canvas right-border?
if (newLeft > canvas.Margin.Left + canvas.ActualWidth - img.ActualWidth)
newLeft = canvas.Margin.Left + canvas.ActualWidth - img.ActualWidth;
// newLeft inside canvas left-border?
else if (newLeft < canvas.Margin.Left)
newLeft = canvas.Margin.Left;
img.SetValue(Canvas.LeftProperty, newLeft);
double newTop = e.GetPosition(canvas).Y - firstYPos - canvas.Margin.Top;
// newTop inside canvas bottom-border?
if (newTop > canvas.Margin.Top + canvas.ActualHeight - img.ActualHeight)
newTop = canvas.Margin.Top + canvas.ActualHeight - img.ActualHeight;
// newTop inside canvas top-border?
else if (newTop < canvas.Margin.Top)
newTop = canvas.Margin.Top;
img.SetValue(Canvas.TopProperty, newTop);
}
}
This code allows me to drag-and-drop the Images inside the Canvas, without leaving the Canvas itself.
Now I just need to be able to do two more things:
Fix a little bug where my Mouse slips of the Image when I drag them around to fast. This happens quite often, even when I'm not even moving the dragging image around THAT fast..
Making it able to drag-and-drop multiple images at once, preferably by selecting multiple first, and then drag-and-drop the whole bunch of them while staying inside the Canvas.
PS: My previously question can be found here.

You'll want to lock the mouse on to the image to stop the cursor slipping off it Mouse.Capture (imageReference), you can release it on mouse up with Mouse.Capture (null) – Andy Feb 18 at 15:58
After using Andy's suggestion, by adding:
Mouse.Capture(img);
at the bottom of the MouseLeftButtonDown-function, and
Mouse.Capture(null);
at the bottom of the PreviewMouseLeftButtonUp-function, it works like a charm. So thanks a lot Andy!

Related

Panning Image in pictureBox not working

I have developed windows application in c# where I have a pictureBox inside a panel. I have applied zoom in and zoom out functionality in it. Now I want the image inside the pictureBox to pan. I have applied mouseDown, mouseMove and mouseUp event on pictureBox. The code for it is:
private void pictureBox2_MouseDown(object sender, MouseEventArgs e)
{
if (pflag == 1)
{
dragging = true;
start = e.Location;
}
}
private void pictureBox2_MouseMove(object sender, MouseEventArgs e)
{
// panning code
if (pflag == 1)
{
if (dragging && zoom == 1)
{
pictureBox2.Location = new Point(pictureBox2.Left + (e.Location.X - start.X), pictureBox2.Top + (e.Location.Y - start.Y));
}
}
}
private void pictureBox2_MouseUp(object sender, MouseEventArgs e)
{
if (pflag == 1)
{
dragging = false;
}
}
Here the image is panning but with no boundary control. Sometimes even the image goes below the panel area while panning. What I need here is, image should move top, left , right, bottom according to zoom factor i.e like how scroll bar works and not beyond that.
You don't need to worry about zoom as the mouse coordinates will be fine as they are. The distance of the shown pixels should be the same as those the cursor is moving..
You also do not really need the dragging variable, unless you use it for something else.
However you do need to check the mouse button during the MouseMove:
if (pflag == 1 && e.Button == System.Windows.Forms.MouseButtons.Left )
Do note few things:
The user expects that the spot he drags stays with the mouse cursor just as the pixel he touches should always move with the fingertip. Do not surprise him by scaling in the zoom-factor!
If you wanted to do that you would need to use a factor, not adding an number.
Yes, the scrollbars will factor in the zoom but also the lift will still stay with the mouse!
Here is an example of how to set limits to prevent the user from going too far. It it a little involved because it needs to work when zoomed in or out. Do not start with illegal positions, though, nor get into those while zooming!
// panning code
if ( pflag == 1 && e.Button == System.Windows.Forms.MouseButtons.Left )
{
{
Rectangle panRect = new Rectangle(panel1.Location, panel1.ClientSize);
Rectangle picRect = new Rectangle(pictureBox2.Location, pictureBox2.ClientSize);
int newLeft = pictureBox2.Left + (e.Location.X - start.X);
int newTop = pictureBox2.Top + (e.Location.Y - start.Y);
int newRight = newLeft + picRect.Width;
int newBottom = newTop + picRect.Height;
if ((newLeft < 0 && newRight < panRect.Width)
|| (newLeft > 0 /*&& newRight > panRect.Width */)) newLeft = picRect.Left;
if ((newTop < 0 && newBottom < panRect.Width)
|| (newTop > 0 /*&& newBottom > panRect.Height*/)) newTop = picRect.Top;
pictureBox2.Location = new Point(newLeft, newTop);
}
Text = "" + pictureBox2.Location;
}
Note the two parts I have commented out! As it is you can't move a picture that is smaller than the viewport; you can allow it by removing the comments but should then take care when zooming in to move it up and left to zero as it should never sit in the positve range and also overlap or else the scrollbars will behave in a weird way..!

rectangle drawn in different point when canvas is zoomed

I have a canvas which has a zooming function. There are a lot of elements inside of it so, for selection I was going to use a selection box which I create dynamically when selection box is clicked. On clicking the button, I add the rectangle to the canvas and again, on clicking the button, I remove it.
I have the following xaml code:
<Viewbox x:Name="vbCanvas">
<Grid x:Name="theGrid"
MouseDown="Grid_MouseDown"
MouseUp="Grid_MouseUp"
MouseMove="Grid_MouseMove"
Background="Transparent">
<Canvas Name="canvasWaSNA" Margin="0,10,10,10" Height="720" Width="1280">
</Canvas>
</Grid>
</Viewbox>
mouse events of theGrid draws the rectangle on runtime on the canvas. The codes for those events are:
bool mouseDown = false;
Point mouseDownPos;
Point mouseUpPos;
private void Grid_MouseDown(object sender, MouseButtonEventArgs e)
{
mouseDown = true;
mouseDownPos = e.GetPosition(theGrid);
theGrid.CaptureMouse();
// Initial placement of the drag selection box.
Canvas.SetLeft(sBox, mouseDownPos.X);
Canvas.SetTop(sBox, mouseDownPos.Y);
sBox.Width = 0;
sBox.Height = 0;
// Make the drag selection box visible.
sBox.Visibility = Visibility.Visible;
}
}
private void Grid_MouseUp(object sender, MouseButtonEventArgs e)
{
// Release the mouse capture and stop tracking it.
mouseDown = false;
mouseUpPos = e.GetPosition(theGrid);
theGrid.ReleaseMouseCapture();
// Show the drag selection box.
sBox.Visibility = Visibility.Visible;
MessageBox.Show(mouseDownPos.ToString() + " " + mouseUpPos.ToString());
}
private void Grid_MouseMove(object sender, MouseEventArgs e)
{
if (mouseDown)
{
// When the mouse is held down, reposition the drag selection box.
Point mousePos = e.GetPosition(theGrid);
if (mouseDownPos.X < mousePos.X)
{
Canvas.SetLeft(sBox, mouseDownPos.X);
sBox.Width = mousePos.X - mouseDownPos.X;
}
else
{
Canvas.SetLeft(sBox, mousePos.X);
sBox.Width = mouseDownPos.X - mousePos.X;
}
if (mouseDownPos.Y < mousePos.Y)
{
Canvas.SetTop(sBox, mouseDownPos.Y);
sBox.Height = mousePos.Y - mouseDownPos.Y;
}
else
{
Canvas.SetTop(sBox, mousePos.Y);
sBox.Height = mouseDownPos.Y - mousePos.Y;
}
}
}
To create a Rectangle at runtime, I have to click a button. The event of that button is as follows:
private void select_Click_1(object sender, RoutedEventArgs e)
{
if (!canvasWaSNA.Children.Contains(sBox))
{
sBox.Name = "selectionBox";
sBox.StrokeThickness = 1.5 / zoomfactor;
sBox.StrokeDashArray = new DoubleCollection { 1, 2 };
sBox.Visibility = System.Windows.Visibility.Collapsed;
sBox.Stroke = Brushes.Gray;
canvasWaSNA.Children.Add(sBox);
}
else
{
sBox.Visibility = System.Windows.Visibility.Collapsed;
canvasWaSNA.Children.Remove(sBox);
}
}
I am using the following code to zoom into the canvas:
double zoomfactor = 1.0;
void window_MouseWheel(object sender, MouseWheelEventArgs e)
{
Point p = e.MouseDevice.GetPosition(canvasWaSNA); //gets the location of the canvas at which the mouse is pointed
Matrix m = canvasWaSNA.RenderTransform.Value;
if (e.Delta > 0)
{ //the amount of wheel of mouse changed. e.Delta holds int value.. +ve for uproll and -ve for downroll
m.ScaleAtPrepend(1.1, 1.1, p.X, p.Y);
zoomfactor *= 1.1;
}
else
{
m.ScaleAtPrepend(1 / 1.1, 1 / 1.1, p.X, p.Y);
zoomfactor /= 1.1;
}
canvasWaSNA.RenderTransform = new MatrixTransform(m);
}
When my canvas is on original size, The rectangle is drawn perfectly but as I zoom in or zoom out, rectangle is drawn abnormally. It starts to draw from other points. What might be the problem? Please help
Well, I wasnot supposed to capture the mouse position with respect to theGrid, as I had to create the rectangle with respect to canvas. So, I have to get the position as e.GetPosition(canvasWaSNA) and the intended result was shown. It captured the mouse position on the canvas. Now, the rectangle is drawn perfectly even when zoomed in or zoomed out.
Also, I improved the StrokeThickness of the rectangle drawn by referencing it with the zoomfactor of the canvas.
private void Grid_MouseDown(object sender, MouseButtonEventArgs e)
{mouseDown = true;
mouseDownPos = e.GetPosition(canvasWaSNA);
theGrid.CaptureMouse();
sBox.StrokeThickness = 1.5 / zoomfactor;
// Initial placement of the drag selection box.
Canvas.SetLeft(sBox, mouseDownPos.X);
Canvas.SetTop(sBox, mouseDownPos.Y);
sBox.Width = 0;
sBox.Height = 0;
// Make the drag selection box visible.
sBox.Visibility = Visibility.Visible;
}

C# Drag and Drop Image within Canvas

I tried to Google how to make drag & drop for UIElements on a Canvas, but couldn't find anything that I'm looking for.
I got a C# WPF application with a Window. Inside the Window I got a Canvas where I can add Images to.
What I want is to be able to Drag & Drop the Images, while staying within the Canvas' borders.
I also want this to be in code, so not in the xaml.
I got this in the function where I add/update the Images to the Canvas. The TODO's should be replaced for the Drag & Drop events.
Image img = ImageList[i].Image;
img.Name = "Image" + i;
// TODO: Drag and Drop event for Image
// TODO: Check if Left and Top are within Canvas (minus width / height of Image)
Canvas.SetLeft(img, Left); // Default Left when adding the image = 0
Canvas.SetTop(img, Top); // Default Top when adding the image = 0
MyCanvas.Children.Add(img);
OnPropertyChanged("MyCanvas");
PS: Though this is for later, if someone has code to drag and drop multiple images at once as an additional bonus, I would appreciate it.
Thanks in advance for the help.
Fixed my problem below, by using the following code:
img.AllowDrop = true;
img.PreviewMouseLeftButtonDown += this.MouseLeftButtonDown;
img.PreviewMouseMove += this.MouseMove;
img.PreviewMouseLeftButtonUp += this.PreviewMouseLeftButtonUp;
private object movingObject;
private double firstXPos, firstYPos;
private void MouseLeftButtonDown(object sender, MouseButtonEventArgs e) {
// In this event, we get the current mouse position on the control to use it in the MouseMove event.
Image img = sender as Image;
Canvas canvas = img.Parent as Canvas;
firstXPos = e.GetPosition(img).X;
firstYPos = e.GetPosition(img).Y;
movingObject = sender;
// Put the image currently being dragged on top of the others
int top = Canvas.GetZIndex(img);
foreach (Image child in canvas.Children)
if (top < Canvas.GetZIndex(child))
top = Canvas.GetZIndex(child);
Canvas.SetZIndex(img, top + 1);
}
private void PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e) {
Image img = sender as Image;
Canvas canvas = img.Parent as Canvas;
movingObject = null;
// Put the image currently being dragged on top of the others
int top = Canvas.GetZIndex(img);
foreach (Image child in canvas.Children)
if (top > Canvas.GetZIndex(child))
top = Canvas.GetZIndex(child);
Canvas.SetZIndex(img, top + 1);
}
private void MouseMove(object sender, MouseEventArgs e) {
if (e.LeftButton == MouseButtonState.Pressed && sender == movingObject) {
Image img = sender as Image;
Canvas canvas = img.Parent as Canvas;
double newLeft = e.GetPosition(canvas).X - firstXPos - canvas.Margin.Left;
// newLeft inside canvas right-border?
if (newLeft > canvas.Margin.Left + canvas.ActualWidth - img.ActualWidth)
newLeft = canvas.Margin.Left + canvas.ActualWidth - img.ActualWidth;
// newLeft inside canvas left-border?
else if (newLeft < canvas.Margin.Left)
newLeft = canvas.Margin.Left;
img.SetValue(Canvas.LeftProperty, newLeft);
double newTop = e.GetPosition(canvas).Y - firstYPos - canvas.Margin.Top;
// newTop inside canvas bottom-border?
if (newTop > canvas.Margin.Top + canvas.ActualHeight - img.ActualHeight)
newTop = canvas.Margin.Top + canvas.ActualHeight - img.ActualHeight;
// newTop inside canvas top-border?
else if (newTop < canvas.Margin.Top)
newTop = canvas.Margin.Top;
img.SetValue(Canvas.TopProperty, newTop);
}
}
This code allows me to drag-and-drop the Images inside the Canvas, without leaving the Canvas itself.
Now I just need to be able to do two more things:
Fix a little bug where my Mouse slips of the Image when I drag them around to fast. This happens quite often, even when I'm not even moving the dragging image around THAT fast.. Fixed by using the solution mentioned in my other question.
Making it able to drag-and-drop multiple images at once, preferably by selecting multiple first, and then drag-and-drop the whole bunch of them while staying inside the Canvas.
Will make a new Question for this.
I was did a project that uses a chunk of your code and does drag and drop on canvas, look into it and see if there be any difference, dont really have the time to check
private void pinCanvas_PreviewMouseLeftButtonDown_1(object sender, MouseButtonEventArgs e)
{
// Point pt = e.GetPosition(pinCanvas);
// Curosor.Text = String.Format("You are at ({0}in, {1}in) in window coordinates", (pt.X / (96 / 72)) * 1/72, (pt.Y / (96 / 72)) * 1/72);
}
bool captured = false;
double x_shape, x_canvas, y_shape, y_canvas;
UIElement source = null;
string elementName;
double elementHeight, elementWidth;
private void pinCanvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
setCanvasSize();
source = (UIElement)sender;
elementName = ((Label)source).Name;
switch (elementName)
{
case "pinTextBox" :
elementHeight = pinActualHeight;
elementWidth = pinActualWidth;
break;
case "serialTextBox" :
elementHeight = serialActualHeight;
elementWidth = serialActualWidth;
break;
case "batchTextBox" :
elementHeight = batchActualHeight;
elementWidth = batchActualWidth;
break;
}
Mouse.Capture(source);
captured = true;
x_shape = Canvas.GetLeft(source);
x_canvas = e.GetPosition(Maincanvas).X;
y_shape = Canvas.GetTop(source);
y_canvas = e.GetPosition(Maincanvas).Y;
}
private void pinCanvas_MouseMove(object sender, MouseEventArgs e)
{
if (captured)
{
double x = e.GetPosition(Maincanvas).X;
double y = e.GetPosition(Maincanvas).Y;
var xCond = Math.Round(appActivities.DIP2Inch(x_shape), 4).ToString();
var yCond = Math.Round(appActivities.DIP2Inch(y_shape), 4).ToString();
var name = ((Label)source).Name;
x_shape += x - x_canvas;
// if ((x_shape < Maincanvas.ActualWidth - elementWidth) && x_shape > 0)
// {
Canvas.SetLeft(source, x_shape);
switch (name)
{
case "pinTextBox" :
pinOffsetLeft.Text = xCond;
break;
case "serialTextBox" :
serialOffsetLeft.Text = xCond;
break;
case "batchTextBox" :
batchOffsetLeft.Text = xCond;
break;
}
// }
x_canvas = x;
y_shape += y - y_canvas;
// if (y_shape < Maincanvas.ActualHeight - elementHeight && y_shape > 0)
// {
Canvas.SetTop(source, y_shape);
switch (name)
{
case "pinTextBox":
pinOffsetTop.Text = yCond;
break;
case "serialTextBox":
serialOffsetTop.Text = yCond;
break;
case "batchTextBox":
batchOffsetTop.Text = yCond;
break;
}
// }
y_canvas = y;
}
}
private void pinCanvas_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
Mouse.Capture(null);
captured = false;
// MessageBox.Show((Canvas.GetTop(source)).ToString());
/* if (Canvas.GetTop(source) < 0)
{
Canvas.SetTop(source, 0);
}
if (Canvas.GetLeft(source) < 0)
{
Canvas.SetLeft(source, 0);
}
if (Canvas.GetLeft(source) > Maincanvas.ActualWidth - elementWidth)
{
// MessageBox.Show("Left Too Much " + (Canvas.GetLeft(source) * 1/96).ToString());
Canvas.SetLeft(source, Maincanvas.ActualWidth - elementWidth);
}
if (Canvas.GetTop(source) > Maincanvas.ActualHeight - elementHeight)
{
Canvas.SetTop(source, Maincanvas.ActualHeight - elementHeight);
} */
oneElemntTorched = true;
//MessageBox.Show(this.pinTextBox.ActualHeight.ToString() + ", " + this.pinTextBox.ActualWidth.ToString());
}

Set autoscroll position on mouse move

I need to update scroll bar position when I click on image and move picturebox. It is always at the beggining, it only moving on the right side (horizontall) and down (vertical).
private void pictureBox1_MouseMove_1(object sender, MouseEventArgs e)
{
....
Point currentMousePos = e.Location;
int distanceX = currentMousePos.X - mouseX;
int distanceY = currentMousePos.Y - mouseY;
int newX = pictureBox1.Location.X + distanceX;
int newY = pictureBox1.Location.Y + distanceY;
if (newX + pictureBox1.Image.Width + 10 < pictureBox1.Image.Width && pictureBox1.Image.Width + newX + 10 > panel1.Width)
{
pictureBox1.Location = new Point(newX, pictureBox1.Location.Y);
}
if (newY + pictureBox1.Image.Height + 10 < pictureBox1.Image.Height && pictureBox1.Image.Height + newY + 10 > panel1.Height)
{
pictureBox1.Location = new Point(pictureBox1.Location.X, newY);
}
}
I think you need to change the AutoScrollPosition of the parent panel and not play around with the Location points of the PictureBox. After all, the scroll bars of the parent panel are already taking care of the position of the PictureBox.
Try something like this (by the way, my code only does this when a button is pressed, otherwise, I think it would be a weird user interface design):
private Point _StartPoint;
void pictureBox1_MouseDown(object sender, MouseEventArgs e) {
if (e.Button == MouseButtons.Left)
_StartPoint = e.Location;
}
void pictureBox1_MouseMove(object sender, MouseEventArgs e) {
if (e.Button == MouseButtons.Left) {
Point changePoint = new Point(e.Location.X - _StartPoint.X,
e.Location.Y - _StartPoint.Y);
panel1.AutoScrollPosition = new Point(-panel1.AutoScrollPosition.X - changePoint.X,
-panel1.AutoScrollPosition.Y - changePoint.Y);
}
}
LarsTech's code isn't 100% correct. 2 notes:
Note that if slider is moved, then the same point on screen changes it's coordinates relative to pictureBox1 (as pictureBox moved with moved slider). Therefore we want to use the screen coordinates (Control.MousePosition instead of e.Location).
Changing panel1.AutoScrollPosition causes the move of pictureBox relative to mouseCursor, so the pictureBox1.MouseMove event is fired again, even if cursor didn't move on the screen. Adding _StartPoint = Control.MousePosition prevents unwanted scrolling.

Track cusor location and add image from cusor location into PDF with iTextSharp

I'm looking for the most appropriate way to allow the user to import an image to a PDF and allow them to drag the picture around the PDF/winform and specify where the image is placed.
I'm thinking the best way to go about doing this is pulling the location from the cusor.
Something like:
Rectangle rect = new Rectangle(400, 772, 545, 792);
Instead of pre-defined coordinates, have the output be the selected cursor location of the user.
Any help would be very much appreciated.
Thank you in advance!
Users might have a hard time picking an image location just by pressing the mouse cursor on a form. Instead I recommend allowing them to drag a relatively sized rectangle around a grid. You'll have to translate coordinates appropriately, including fixing the Y value since iTextSharp starts at the bottom left instead of the top left, but that shouldn't be too hard.
Below is a full working C# 2010 WinForms app that allows you to drag a red rectangle around a black square. The comments in the code should pretty much explain everything. It has one big problem that need to be addressed, it stores the X/Y coordinates are screen-based and not form based, so if you drag once, move the entire form and drag again it will get "funky". This can be solved by calculating the x/y relative to the form instead which I'll leave up to you.
Hopefully this gets you down a path that works for you!
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
//Basic dimensions of our "border" and our "image". Assumes 72 dots per inch which isn't technically correct but gives us something to work with
private int BORDER_WIDTH = (int)11 * 72;
private int BORDER_HEIGHT = (int)8.5 * 72;
private int IMAGE_WIDTH = (int)2 * 72;
private int IMAGE_HEIGHT = (int)3 * 72;
private int IMAGE_OFFSET = 5;
//These will store the x/y when we press our mouse down so that we can calculate the drag later
private int offsetX;
private int offsetY;
//Our main "image" that we'll move around
PictureBox pb;
//The "border" to move the image around in
PictureBox border;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//Resize the form and make it not user-resizable
this.Size = new Size(BORDER_WIDTH + 30, BORDER_HEIGHT + 50);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
//Create our "image"
pb = new PictureBox();
pb.Size = new Size(IMAGE_WIDTH, IMAGE_HEIGHT);
pb.Location = new Point(IMAGE_OFFSET, IMAGE_OFFSET);
pb.BackColor = Color.Red;
//Bind a handler to the mouse down event
pb.MouseDown += new MouseEventHandler(this.pbMouseDown);
this.Controls.Add(pb);
//Create our "border"
border = new PictureBox();
border.Size = new Size(BORDER_WIDTH, BORDER_HEIGHT);
border.Location = new Point(IMAGE_OFFSET, IMAGE_OFFSET);
border.BackColor = Color.Black;
this.Controls.Add(border);
}
private void pbMouseDown(object sender, MouseEventArgs e)
{
//Store the current x/y so that we can use them in calculations later
offsetX = e.X;
offsetY = e.Y;
//When the mouse is down we want to remove the original mouse down handler
pb.MouseDown -= new MouseEventHandler(this.pbMouseDown);
//Add to more handler looking for mouse up and mouse movement
pb.MouseUp += new MouseEventHandler(this.pbMouseUp);
pb.MouseMove += new MouseEventHandler(this.pbMouseMove);
}
private void pbMouseUp(object sender, MouseEventArgs e)
{
//When the mouse button is released, remove old handlers and add back the down event
pb.MouseMove -= new MouseEventHandler(this.pbMouseMove);
pb.MouseUp -= new MouseEventHandler(this.pbMouseUp);
pb.MouseDown += new MouseEventHandler(this.pbMouseDown);
//Pop up a message, this is where something with iTextSharp would be done
MessageBox.Show(String.Format("The top left of the image is at {0}x{1}", pb.Top - IMAGE_OFFSET, pb.Left - IMAGE_OFFSET));
}
private void pbMouseMove(object sender, MouseEventArgs e)
{
//Calculate where to draw the "image" at next
//First, calculate based on the current image's location, the offset that we stored ealier and the current mouse position
int newLeft = e.X + pb.Left - offsetX;
int newTop = e.Y + pb.Top - offsetY;
//Next, make sure that we haven't gone over one of the boundaries of the "border"
if (newLeft < border.Left) newLeft = border.Left;
if (newTop < border.Top) newTop = border.Top;
if (newLeft + pb.Width > border.Right) newLeft = border.Right - pb.Width;
if (newTop + pb.Height > border.Bottom) newTop = border.Bottom - pb.Height;
//Finally, assign the new value
pb.Left = newLeft;
pb.Top = newTop;
}
}
}

Categories