This is a custom control I have made, a graphical timer, however, it is not working correctly. As the time left decreases a pie is filled to represent the amount of time left decreasing, but it is decreasing with unexpected angles (which are output to the listbox for debugging purposes). How do I get it to work correctly? Also I'm very new to making Custom Controls (this is my first) so any pointers on good coding guidelines, what not to do, etc, would be very helpful.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace TestCustomControl
{
class GraphicalTimer : Control
{
public Color Timer { get; set; }
public Color TimerEmpty { get; set; }
public Color BorderColor { get; set; }
private Timer t;
public int MaxTime { get; set; }
private int timeElapsed = 0;
public GraphicalTimer()
{
DoubleBuffered = true;
SetStyle(ControlStyles.SupportsTransparentBackColor, true);
BackColor = Color.Transparent;
t = new Timer();
t.Interval = 1000;
t.Tick += t_Tick;
}
public void Start()
{
t.Start();
}
public void Stop()
{
t.Stop();
}
public void Reset()
{
timeElapsed = 0;
Invalidate();
}
void t_Tick(object sender, EventArgs e)
{
timeElapsed += 1;
if (timeElapsed == MaxTime)
{
t.Dispose();
}
Invalidate();
}
private float getAngleFromTime()
{
if (timeElapsed == 0)
{
return 0;
}
else
{
MainWindow.lb.Items.Add((360 / (MaxTime / timeElapsed)).ToString());
return (360 / (MaxTime / timeElapsed));
}
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
Graphics g = e.Graphics;
Rectangle rc = ClientRectangle;
g.FillEllipse(new SolidBrush(Timer), rc);
g.FillPie(new SolidBrush(TimerEmpty), rc, -90, getAngleFromTime());
g.DrawEllipse(new Pen(BorderColor, 4), rc);
Font font = new Font("Arial", (float)rc.Height * 0.4f, FontStyle.Bold, GraphicsUnit.Pixel);
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Center;
sf.LineAlignment = StringAlignment.Center;
g.DrawString((MaxTime - timeElapsed).ToString("D2"), font, new SolidBrush(Color.Black), new RectangleF((rc.Width - rc.Width / 2) / 2, (rc.Height - rc.Height / 2) / 2, rc.Width * 0.7f, rc.Height * 0.7f));
}
}
class MainWindow : Form
{
GraphicalTimer gt;
Button startButton;
Button stopButton;
Button resetButton;
public static ListBox lb;
public MainWindow()
{
this.Text = "Test Application";
gt = new GraphicalTimer();
gt.MaxTime = 20;
gt.BorderColor = Color.BurlyWood;
gt.Timer = Color.Aqua;
gt.TimerEmpty = Color.White;
gt.Top = 10;
gt.Left = 10;
gt.Width = 50;
gt.Height = 50;
this.Controls.Add(gt);
startButton = new Button();
startButton.Top = 70;
startButton.Left = 30;
startButton.AutoSize = true;
startButton.Text = "Start Timer";
startButton.Click += startButton_Click;
this.Controls.Add(startButton);
stopButton = new Button();
stopButton.Top = 70;
stopButton.Left = startButton.Right + 10;
stopButton.AutoSize = true;
stopButton.Text = "Stop Timer";
stopButton.Click += stopButton_Click;
this.Controls.Add(stopButton);
resetButton = new Button();
resetButton.Top = 70;
resetButton.Left = stopButton.Right + 10;
resetButton.AutoSize = true;
resetButton.Text = "Reset Timer";
resetButton.Click += resetButton_Click;
this.Controls.Add(resetButton);
lb = new ListBox();
lb.Top = resetButton.Bottom + 10;
lb.Left = 10;
lb.Width = this.ClientSize.Width - 20;
lb.Height = this.ClientSize.Height - lb.Top - 10;
this.Controls.Add(lb);
}
void resetButton_Click(object sender, EventArgs e)
{
gt.Reset();
}
void stopButton_Click(object sender, EventArgs e)
{
gt.Stop();
}
void startButton_Click(object sender, EventArgs e)
{
gt.Start();
}
}
class StartClass
{
static void Main()
{
MainWindow form = new MainWindow();
Application.EnableVisualStyles();
Application.Run(form);
}
}
}
You are using integers to calculate the angle, and in a way that can cause quite some jitters.
360 / (MaxTime / timeElapsed) will first evaluate temp = MaxTime / timeElapsed in integer arithmetics, and then 360 / temp also using integer division.
Try using floating point numbers for the calculation and then converting the final result into an integer value if you need it that way. Even writing 360 * timeElapsed / MaxTime might reduce the artifacts as you then first multiply 360 * timeElapsed which is accurate (unless timeElapsed is very large).
The method of calculating AngleForTime is wrong. Just replace your method with below code and it should do your job.
;)
private float getAngleFromTime()
{
if (timeElapsed == 0)
{
return 0;
}
else
{
MainWindow.lb.Items.Add((360*timeElapsed) / MaxTime ).ToString();
return (360*timeElapsed) / MaxTime ;
}
}
Related
Me and my buddy have been working on this magnifier application and we cannot make it work the way we want it.
The way we would like it to work:
Open app.
Move mouse to area you want magnified.
Hit enter.
Magnifying window moves to (offset) location of mouse and keeps updating that window for that specific location.
Hit enter again to move window to new cursor location.
Right now once i hit enter, the window follows the mouse because it goes into a for loop where it grabs "Cursor.Position". I've tried to save the Cursor.Position value at the "OnkeyDown" event and use it inside the timer loop but that won't work since it "does not exist in current context".
Can anyone see how i can do this?
Thanks in advance!
/Morten
/* O-button zooms out
* I-button zooms in
* Esc-button exits app
* Enter moves magnifying window to new location (doesn't work)
*/
using System;
using System.Drawing;
using System.Windows.Forms;
namespace Magnifier
{
public partial class Form1 : Form
{
Bitmap printscreen = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
PictureBox pictureBox1 = new PictureBox();
int zoom = 3; //zoom level
public bool NewZoomLocation = false;
public Form1()
{
{
InitializeComponent();
pictureBox1.Dock = DockStyle.Fill;
pictureBox1.BorderStyle = BorderStyle.FixedSingle;
Controls.Add(pictureBox1);
FormBorderStyle = FormBorderStyle.None;
Timer timer = new Timer();
timer.Interval = 100;
timer.Tick += timer_Tick;
timer.Start();
}
void timer_Tick(object sender, EventArgs e)
{ var position = Cursor.Position;
int xlocation = position.X;
int ylocation = position.Y;
{
try
{
var graphics = Graphics.FromImage(printscreen as Image);
graphics.CopyFromScreen(0, 0, 0, 0, printscreen.Size);
GC.Collect(); // Force the garbage collector (deals with memory leak)
if (NewZoomLocation == true)
{
var lensbmp = new Bitmap(50, 50); //Bitmap for Zoom window
var i = 0;
var j = 0;
for (int row = xlocation - 25; row < xlocation + 25; row++)
{
j = 0;
for (int column = ylocation - 25; column < ylocation + 25; column++)
{
lensbmp.SetPixel(i, j, printscreen.GetPixel(row, column));
j++;
}
i++;
}
this.pictureBox1.Image = new Bitmap(lensbmp, lensbmp.Width * zoom, lensbmp.Height * zoom);
Size = pictureBox1.Image.Size;
Left = xlocation - 45 * (zoom); //Horisontal position of final zoom window
Top = ylocation + 30; //Vertical position of final zoom window
TopMost = true;
}
}
catch //(Exception ex)
{
//MessageBox.Show(ex.Message);
}
}
}
}
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.KeyValue == 73) // I-button to zoom in
zoom++;
else if (e.KeyValue == 79) // O-button to zoom in
zoom--;
else if (e.KeyValue == 27) // Esc-button to exit
{
Close();
Dispose();
}
else if (e.KeyValue == 13) // Enter-button to choose zoon area
{
NewZoomLocation = true;
}
base.OnKeyDown(e);
}
}
}
I'm not really sure what you want to achieve here, however this should get you in a better place.
First thing first. The use of GC.Collect its because you are trying to plug a memory leak, if you ever create an image, dispose of it.
Given some globals
private readonly PictureBox pictureBox1 = new PictureBox();
private Bitmap _lastBmp = new Bitmap(300, 300);
private Point _position;
public bool NewZoomLocation;
private int zoom = 3; //zoom level
Constructor
public Form1()
{
InitializeComponent();
pictureBox1.Dock = DockStyle.Fill;
pictureBox1.BorderStyle = BorderStyle.FixedSingle;
Controls.Add(pictureBox1);
FormBorderStyle = FormBorderStyle.None;
KeyPreview = true;
Size = _lastBmp.Size;
TopMost = true;
var timer = new Timer();
timer.Interval = 100;
timer.Tick += timer_Tick;
timer.Start();
}
Cleanup
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
_lastBmp.Dispose();
_lastBmp = null;
}
Keydown
protected override void OnPreviewKeyDown(PreviewKeyDownEventArgs e)
{
base.OnPreviewKeyDown(e);
switch (e.KeyCode)
{
case Keys.Enter:
NewZoomLocation = true;
_position = Cursor.Position;
break;
case Keys.Up:
zoom++;
break;
case Keys.Down:
zoom--;
break;
case Keys.Escape:
Close();
break;
}
}
Timer
private void timer_Tick(object sender, EventArgs e)
{
if (NewZoomLocation)
{
var w = _lastBmp.Size.Width / zoom;
var h = _lastBmp.Size.Height / zoom;
var x = _position.X - w / 2;
var y = _position.Y - h / 2;
var size = new Size(w, h);
using (var screen = new Bitmap(size.Width, size.Height))
{
using (var g = Graphics.FromImage(screen))
{
g.CopyFromScreen(new Point(x, y), Point.Empty, size);
}
// resize
using (var g = Graphics.FromImage(_lastBmp))
{
g.DrawImage(screen, new Rectangle(new Point(), _lastBmp.Size), new Rectangle(0, 0, w, h), GraphicsUnit.Pixel);
}
}
pictureBox1.Image = _lastBmp;
}
}
There is a lot more that can be done with this, however it should get you started. There is no memory leak anymore, it only grabs a screen shot of what it needs so will be faster.
Good luck
I've got a User Control consisting of Panels and Labels.
MinPanel, ValuePanel, and MaxPanel.
I'm trying to allow the user to drag the panels much like you would in a TrackBar.
My problem is that when I click and attempt to drag the MinPanel, it jump around starting at 0, then to 200, then to other random values. It seems to be attempting to reset to it's default value each time I drag it.
public partial class ToolboxCustomTrackBar : UserControl
{
private int min = 0;
private int max = 1000;
private int selectedMin = 0;
private int selectedMax = 1000;
private int selectedValue = 400;
private int selectionWidth = 0;
private int labelHeight = 10;
public int Min
{
get { return min; }
set
{
min = value;
Invalidate();
}
}
public int Max
{
get { return max; }
set
{
max = value;
Invalidate();
}
}
public int SelectedMin
{
get { return selectedMin; }
set
{
selectedMin = value;
Invalidate();
}
}
public int SelectedMax
{
get { return selectedMax; }
set
{
selectedMax = value;
Invalidate();
}
}
public int SelectedValue
{
get { return selectedValue; }
set { selectedValue = value; Invalidate(); }
}
public int LabelHeight
{
get { return labelHeight; }
set { labelHeight = value; Invalidate(); }
}
public ToolboxCustomTrackBar()
{
InitializeComponent();
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
backdropPanel.Width = Width;
backdropPanel.Height = Height;
SelectedMin = Min;
SelectedMax = Max;
SelectedValue = (Max - Min) / 2;
selectionWidth = Max - Min;
Invalidate();
backdropPanel.BackColor = Color.LightBlue;
minPanel.BackColor = Color.DarkRed;
maxPanel.BackColor = Color.DarkGreen;
valuePanel.BackColor = Color.Black;
backdropPanel.Location = new Point(Min, backdropPanel.Location.Y);
}
private void ToolboxCustomTrackBar_Paint(object sender, PaintEventArgs e)
{
backdropPanel.Location = new Point(0, LabelHeight);
backdropPanel.Width = Width;
backdropPanel.BackColor = Color.AliceBlue;
minPanel.Location = new Point(SelectedMin * Width / (Max - Min), backdropPanel.Location.Y);
maxPanel.Location = new Point(SelectedMax * Width / (Max - Min), backdropPanel.Location.Y);
valuePanel.Location = new Point((SelectedValue) * Width / (Max - Min), backdropPanel.Location.Y);
minLabel.Location = new Point(SelectedMin - (minLabel.Width / 2) + (minPanel.Width / 2), backdropPanel.Location.Y - LabelHeight);
minLabel.Text = SelectedMin.ToString();
maxLabel.Location = new Point(SelectedMax - (maxLabel.Width / 2) + (maxPanel.Width / 2), backdropPanel.Location.Y - LabelHeight);
maxLabel.Text = SelectedMax.ToString();
valueLabel.Location = new Point(SelectedValue - (valueLabel.Width / 2) + (valuePanel.Width / 2), backdropPanel.Location.Y - LabelHeight);
valueLabel.Text = SelectedValue.ToString();
}
private void minPanel_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button != MouseButtons.Left) return; //ensure user left-clicked
int pointedValue = Min + e.X * (Max - Min) / Width; //selectionWidth?
SelectedMin = pointedValue;
}
}
I've cut some unrelated bits out.
I don't fully understand why, but I need to use += instead of =.
private void minPanel_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button != MouseButtons.Left) return; //ensure user left-clicked
int pointedValue = Min + e.X * (Max - Min) / Width;
SelectedMin += pointedValue;
}
I am trying to create a car game using pictureboxes and timers
Here is my code
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
PictureBox car = new PictureBox();
Timer t = new Timer();
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
//Right arrow key
if (e.KeyCode.Equals(Keys.Right) && carPlayer.Location.X < 300)
{
int x = carPlayer.Location.X + 5;
int y = carPlayer.Location.Y;
int width = carPlayer.Size.Width;
int height = carPlayer.Size.Height;
carPlayer.SetBounds(x, y, width, height);
}
//Left arrow key
if (e.KeyCode.Equals(Keys.Left) && carPlayer.Location.X > 35)
{
int x = carPlayer.Location.X - 5;
int y = carPlayer.Location.Y;
int width = carPlayer.Size.Width;
int height = carPlayer.Size.Height;
carPlayer.SetBounds(x, y, width, height);
}
if (e.KeyCode.Equals(Keys.Space))
{
spawnCar();
}
}
void spawnCar()
{
string[] cars = { "data/car_red.png", "data/car_blue.png", "data/car_green.png", "data/car_grey.png" };
Random rand = new Random();
car.SizeMode = PictureBoxSizeMode.StretchImage;
car.Image = Image.FromFile(cars[rand.Next(0, 4)]);
car.Visible = true;
if (rand.Next(0,2) == 0)
{
car.SetBounds(100, 10, 50, 85);
}
else
{
car.SetBounds(250, 10, 50, 85);
}
this.Controls.Add(car);
car.BringToFront();
t.Interval = 1;
t.Tick += new EventHandler(t_Tick);
t.Start();
}
private void t_Tick(object sender, EventArgs e)
{
if (car.Bounds.IntersectsWith(carPlayer.Bounds))
{
t.Stop();
car.Image = Image.FromFile("data/car_wreck.png");
carPlayer.Image = Image.FromFile("data/player_wreck.png");
}
if (car.Bounds.Y > 340)
{
t.Stop();
this.Controls.Remove(car);
}
else
{
car.Top++;
}
}
}
http://i.stack.imgur.com/NhCgY.png
Now when I press space once the car appears at the top and moves down slowly and disappears on reaching the bottom but when I press space multiple time the speed of the car gets faster and faster .
Anyone please help me make the car move at same speed everytime it is created.
Thanks
The problem is that you are registering a new Tick event handler with each car spawn, you only want to do this once. However, there isn't an easy way to check if a handler has been assigned yet so I would recommend using a global flag...
//at class level
bool eventSet = false;
//in spawn method
t.Interval = 1;
if(!eventSet)//check if no handler assigned yet
{
t.Tick += new EventHandler(t_Tick);
eventSet = true;
}
t.Start();
Alternatively, you could attempt to remove the handler before assigning...
//in spawn method
t.Interval = 1;
t.Tick -= new EventHandler(t_Tick);//remove previous one if it exists
t.Tick += new EventHandler(t_Tick);
t.Start();
I'd like to draw animation where the airplane crossing form from leftside to the right.
public partial class Form1 : Form
{
Bitmap sky, plane, background;
int currentX, currentY;
Random rndHeight;
Rectangle planeRect;
Graphics g;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
sky = new Bitmap("sky.jpg");
plane = new Bitmap("plane1.png");
int planeWidth = plane.Width; int planeHeight = plane.Height;
}
catch (Exception) { MessageBox.Show("No files!"); }
this.ClientSize = new System.Drawing.Size(sky.Width, sky.Height);
this.FormBorderStyle = FormBorderStyle.FixedSingle;
background = new Bitmap(sky);
g = Graphics.FromImage(background);
rndHeight = new Random();
currentX = -plane.Width; currentY = rndHeight.Next(0, this.Height);
this.BackgroundImage = background;
timer1.Interval = 1;
timer1.Enabled = true;
timer1.Start();
}
protected override void OnPaint(PaintEventArgs e)
{
e.Graphics.DrawImage(sky, 0, 0);
e.Graphics.DrawImage(plane, planeRect);
}
private void timer1_Tick(object sender, EventArgs e)
{
g.DrawImage(sky, 0, 0);
planeRect.X = currentX; planeRect.Y = currentY; planeRect.Width = plane.Width; planeRect.Height = plane.Height;
g.DrawImage(plane, planeRect);
Rectangle myNewPlane = new Rectangle(planeRect.X - 10, planeRect.Y - 10, planeRect.Width + 20, planeRect.Height + 20);
this.Invalidate(myNewPlane);
if (currentX >= this.Width) currentX = -plane.Width; else currentX += 2;
currentY += rndHeight.Next(-2, 2);
}
}
This code works, but the Rectangle of plane flickers with the frequency of timer1.Interval. My question is: how can I avoid these flickers?
p.s.: background image resolution 1024x768; plane - 160x87. plane is transparent
You fix this by setting the DoubleBuffering style for your Form to remove the flicker, e.g.
DoubleBuffered = true;
You probably want to set a few more control styles as well for automatic double-buffering (after InitializeComponents)
this.SetStyle(
ControlStyles.AllPaintingInWmPaint |
ControlStyles.UserPaint |
ControlStyles.DoubleBuffer,true);
More information about automatic and manual double-buffering is on MSDN here
This is the code:
private void hsMagnfier_OnMouseDown(object sender)
{
int x = mLastCursorPosition.X;
int y = mLastCursorPosition.Y;
MagnifierForm magnifier = new MagnifierForm(mConfiguration, System.Windows.Forms.Cursor.Position);//mLastCursorPosition);
magnifier.Show();
}
This code above is in a Form which I can drag over the screen.
Then when I click on an icon it's doing the magnifier.Show(); and the magnifier form is shown up where the mouse current position is.
But if I click on it again so now the position of the new form the magnifier is in my Form1 center. And not where the mouse current position as in the first time.
This is the MagnifierForm code maybe first time it's in the current mouse position but in the next time/s it's in the center of Form1 ?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
using System.IO;
using System.Drawing.Imaging;
namespace ScreenVideoRecorder
{
public partial class MagnifierForm : Form
{
public MagnifierForm(Configuration configuration, Point startPoint)
{
InitializeComponent();
//--- My Init ---
mConfiguration = configuration;
FormBorderStyle = FormBorderStyle.None;
ShowInTaskbar = mConfiguration.ShowInTaskbar;
TopMost = mConfiguration.TopMostWindow;
Width = mConfiguration.MagnifierWidth;
Height = mConfiguration.MagnifierHeight;
// Make the window (the form) circular
GraphicsPath gp = new GraphicsPath();
gp.AddEllipse(ClientRectangle);
Region = new Region(gp);
mImageMagnifier = Properties.Resources.magnifierGlass;
mTimer = new Timer();
mTimer.Enabled = true;
mTimer.Interval = 20;
mTimer.Tick += new EventHandler(HandleTimer);
mScreenImage = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height);
mStartPoint = startPoint;
mTargetPoint = startPoint;
if (mConfiguration.ShowInTaskbar)
ShowInTaskbar = true;
else
ShowInTaskbar = false;
}
protected override void OnShown(EventArgs e)
{
RepositionAndShow();
}
private delegate void RepositionAndShowDelegate();
private void RepositionAndShow()
{
if (InvokeRequired)
{
Invoke(new RepositionAndShowDelegate(RepositionAndShow));
}
else
{
// Capture the screen image now!
Graphics g = Graphics.FromImage(mScreenImage);
g.CopyFromScreen(0, 0, 0, 0, new Size(mScreenImage.Width, mScreenImage.Height));
g.Dispose();
if (mConfiguration.HideMouseCursor)
Cursor.Hide();
else
Cursor = Cursors.Cross;
Capture = true;
if (mConfiguration.RememberLastPoint)
{
mCurrentPoint = mLastMagnifierPosition;
Cursor.Position = mLastMagnifierPosition;
Left = (int)mCurrentPoint.X - Width / 2;
Top = (int)mCurrentPoint.Y - Height / 2;
}
else
{
mCurrentPoint = Cursor.Position;
}
Show();
}
}
void HandleTimer(object sender, EventArgs e)
{
float dx = mConfiguration.SpeedFactor * (mTargetPoint.X - mCurrentPoint.X);
float dy = mConfiguration.SpeedFactor * (mTargetPoint.Y - mCurrentPoint.Y);
if (mFirstTime)
{
mFirstTime = false;
mCurrentPoint.X = mTargetPoint.X;
mCurrentPoint.Y = mTargetPoint.Y;
Left = (int)mCurrentPoint.X - Width / 2;
Top = (int)mCurrentPoint.Y - Height / 2;
return;
}
mCurrentPoint.X += dx;
mCurrentPoint.Y += dy;
if (Math.Abs(dx) < 1 && Math.Abs(dy) < 1)
{
mTimer.Enabled = false;
}
else
{
// Update location
Left = (int)mCurrentPoint.X - Width / 2;
Top = (int)mCurrentPoint.Y - Height / 2;
mLastMagnifierPosition = new Point((int)mCurrentPoint.X, (int)mCurrentPoint.Y);
}
Refresh();
}
protected override void OnMouseDown(MouseEventArgs e)
{
mOffset = new Point(Width / 2 - e.X, Height / 2 - e.Y);
mCurrentPoint = PointToScreen(new Point(e.X + mOffset.X, e.Y + mOffset.Y));
mTargetPoint = mCurrentPoint;
mTimer.Enabled = true;
}
protected override void OnMouseUp(MouseEventArgs e)
{
if (mConfiguration.CloseOnMouseUp)
{
Close();
mScreenImage.Dispose();
}
Cursor.Show();
Cursor.Position = mStartPoint;
}
protected override void OnMouseMove(MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
mTargetPoint = PointToScreen(new Point(e.X + mOffset.X, e.Y + mOffset.Y));
mTimer.Enabled = true;
}
}
protected override void OnPaintBackground(PaintEventArgs e)
{
if (mConfiguration.DoubleBuffered)
{
// Do not paint background (required for double buffering)!
}
else
{
base.OnPaintBackground(e);
}
}
protected override void OnPaint(PaintEventArgs e)
{
if (mBufferImage == null)
{
mBufferImage = new Bitmap(Width, Height);
}
Graphics bufferGrf = Graphics.FromImage(mBufferImage);
Graphics g;
if (mConfiguration.DoubleBuffered)
{
g = bufferGrf;
}
else
{
g = e.Graphics;
}
if (mScreenImage != null)
{
Rectangle dest = new Rectangle(0, 0, Width, Height);
int w = (int)(Width / mConfiguration.ZoomFactor);
int h = (int)(Height / mConfiguration.ZoomFactor);
int x = Left - w / 2 + Width / 2;
int y = Top - h / 2 + Height / 2;
g.DrawImage(
mScreenImage,
dest,
x, y,
w, h,
GraphicsUnit.Pixel);
}
if (mImageMagnifier != null)
{
g.DrawImage(mImageMagnifier, 0, 0, Width, Height);
}
if (mConfiguration.DoubleBuffered)
{
e.Graphics.DrawImage(mBufferImage, 0, 0, Width, Height);
}
}
//--- Data Members ---
#region Data Members
private Timer mTimer;
private Configuration mConfiguration;
private Image mImageMagnifier;
private Image mBufferImage = null;
private Image mScreenImage = null;
private Point mStartPoint;
private PointF mTargetPoint;
private PointF mCurrentPoint;
private Point mOffset;
private bool mFirstTime = true;
private static Point mLastMagnifierPosition = Cursor.Position;
#endregion
}
}
The first time the new Form the magnifier is shown up where my mouse cursour is.
The next time i click on it's showing the magnifier form in the center of Form1 and not where the mouse cursour is.
Why is that ? When i clikc on the icon again it's still doing the
System.Windows.Forms.Cursor.Position
Again. Strange.
Consider you have two forms - Master and Child
If you are calling Child from Master on MouseUp event(for example), write the code in MouseUp event of Master form
ChildForm obj=new ChildForm();
obj.pntLocation = new Point(Cursor.Position.X, Cursor.Position.Y);
obj.ShowDialog();
Declare a variable inside the Child for location
public Point pntLocation;
Now set location inside the Form_Load of Child
this.Location = pntLocation;
Ok found that the part that doing it is here in the Magnifier form:
mConfiguration.RememberLastPoint = false;
if (mConfiguration.RememberLastPoint)
{
mCurrentPoint = mLastMagnifierPosition;
Cursor.Position = mLastMagnifierPosition;
Left = (int)mCurrentPoint.X - Width / 2;
Top = (int)mCurrentPoint.Y - Height / 2;
}
else
{
mCurrentPoint = Cursor.Position;
}
So I added for now the line: mConfiguration.RememberLastPoint = false; which did the job for now.