How do I reduce the flickering when the form is refreshing? - c#

So when ever I hold the left mouse button and draw the rectangle on the form.
The form itself keeps flickering.
I've tried setting the DoubleBuffered property to true, that didnt change anything.
Is there a way to change the refresh rate or something similar?
Because from what I've tried, the example above and
SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
It doesnt seem to change anything
Here is a gif showing the flickering
https://i.imgur.com/Wa3kmbM.gifv
private void Form1_Load(object sender, EventArgs e)
{
//Hide the Form
this.Hide();
label1.Visible = false;
label2.Visible = false;
//Create the Bitmap (This is an a black bitmap holding just the size.) (Bitmap is mutable)
Bitmap printscreen = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height);
//Create a graphics object that's ready for alteration. `printscreen` is now a graphics Object
Graphics graphics = Graphics.FromImage(printscreen);
//Alter the graphics object which again is the printscreen
graphics.CopyFromScreen(0, 0, 0, 0, printscreen.Size);
//Create a temporary memory stream for the image
using (MemoryStream s = new MemoryStream())
{
//save graphic variable into memory
printscreen.Save(s, ImageFormat.Bmp);
//Set the size of the picturebox
pictureBox1.Size = new Size(Width, Height);
//set the value of the picturebox.Image to an Image.FromStream and load the temp stream
pictureBox1.Image = Image.FromStream(s);
}
//Show Form
this.Show();
//Cross Cursor
Cursor = Cursors.Cross;
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
//startX is holds the corresponding value of where the mouse is in relation to the pixels of the width
//for instance, if it's all the way to the right, it holds the value of 1920.
startX = e.X;
startY = e.Y;
selectPen = new Pen(Color.DimGray, 2);
selectPen.DashStyle = DashStyle.Dash;
pictureBox1.Refresh();
start = true;
}
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (start)
{
pictureBox1.Refresh();
//selectingWidth is equal to how much we have selected from the starting point.
//Let's say the starting point is 10 and our current mouse position is at 10 then we have selected 0 pixels to the right.
//However if we move our mouse 10 pixels to the right it means we have selected 10 pixels to the right.
selectingWidth = e.X - startX;
selectingHeight = e.Y - startY;
//if the selectingWidth is less than 0, then set the origin to the current position of the mouse.
var drawfromX = selectingWidth < 0 ? e.X : startX;
var drawfromY = selectingHeight < 0 ? e.Y : startY;
pictureBox1.Refresh();
pictureBox1.CreateGraphics().DrawRectangle(selectPen,
drawfromX,
drawfromY,
Math.Abs(selectingWidth),
Math.Abs(selectingHeight));
}
}

Related

Why can't it draw a rectangle the opposite way?

So I am trying to recreate the Snipping Tool that comes with Windows.
However I've manage to get it to draw a rectangle from the top left corner and then when I move my cursor to the bottom right.
However if I try to move my cursor from let's say the middle of the screen to the top left it doesnt draw the rectangle.
Why is this?
Here is a GIF showing what happends
https://i.imgur.com/0Y7xXnS.gifv
//These variables control the mouse position
int selectX;
int selectY;
int selectWidth;
int selectHeight;
public Pen selectPen;
//This variable control when you start the right click
bool start;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//Hide the Form
this.Hide();
//Create the Bitmap (This is an a black bitmap holding just the size.) (Bitmap is mutable)
Bitmap printscreen = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height);
//Create a graphics object that's ready for alteration. `printscreen` is now a graphics Object
Graphics graphics = Graphics.FromImage(printscreen);
//Alter the graphics object which again is the printscreen
graphics.CopyFromScreen(0, 0, 0, 0, printscreen.Size);
//Create a temporary memory stream for the image
using (MemoryStream s = new MemoryStream())
{
//save graphic variable into memory
printscreen.Save(s, ImageFormat.Bmp);
//Set the size of the picturebox
pictureBox1.Size = new Size(Width, Height);
//set the value of the picturebox.Image to an Image.FromStream and load the temp stream
pictureBox1.Image = Image.FromStream(s);
}
//Show Form
this.Show();
//Cross Cursor
Cursor = Cursors.Cross;
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
selectX = e.X;
selectY = e.Y;
selectPen = new Pen(Color.DimGray, 1);
selectPen.DashStyle = DashStyle.Solid;
pictureBox1.Refresh();
start = true;
}
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (start)
{
selectWidth = e.X - selectX;
selectHeight = e.Y - selectY;
pictureBox1.Refresh();
pictureBox1.CreateGraphics().DrawRectangle(selectPen,
selectX, selectY, selectWidth, selectHeight);
}
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
Stream sound = Resources.SnapshotSound;
SoundPlayer player = new SoundPlayer(sound);
player.PlaySync();
Application.Exit();
}
}
So what you end up with is basically a rectangle with a negative width and height.
You'll probably want to use the Math.Abs to make sure you get a proper width and height in the cases the difference would become negative.
With that, you will also probably want to draw from different positions based on where your cursor is in relation to the selected point. Something like
selectWidth = e.X - selectX;
selectHeight = e.Y - selectY;
// If width is less than 0, draw from pointer, otherwise from select X
var drawFromX = selectWidth < 0 ? e.X : selectX;
// If height is less than 0, draw from pointer, otherwise from select Y
var drawFromY = selectHeight < 0 ? e.Y : selectY;
pictureBox1.Refresh();
pictureBox1.CreateGraphics().DrawRectangle(selectPen,
drawFromX,
drawFromY,
Math.Abs(selectWidth), // Make sure the rectangle width is positive
Math.Abs(selectHeight)); // Make sure the rectangle height is positive

C# ImageBox Clear Rectangle on MouseUp

I have a panel with multiple picturebox created at runtime.
The user will create a rectangle on any picture box and the selected part will be displayed on a preview picturebox.
I have successfully done the above using the below code.
Question
I want to clear the selection rectangle at mouseup event. Used invalidate but not working.
From how to clear the graphics(rectangle shape) in picturebox
Also, when I scroll the panel the same rectangle(mouse selection) is shown on all picturebox.
private void Picture_Paint(object sender, PaintEventArgs e)
{
if (Rect!=null && Rect.Width>0 && Rect.Height>0)
{
e.Graphics.FillRectangle(selectionBrush, Rect);
}
}
private void Picture_MouseDown(object sender, MouseEventArgs e)
{
RecStartpoint = e.Location;
((PictureBox)sender).Invalidate();
}
private void Picture_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button != MouseButtons.Left) return;
Point tempEndPoint = e.Location;
Rect.Location = new Point(
Math.Min(RecStartpoint.X, tempEndPoint.X),
Math.Min(RecStartpoint.Y, tempEndPoint.Y));
Rect.Size = new Size(
Math.Abs(RecStartpoint.X - tempEndPoint.X),
Math.Abs(RecStartpoint.Y - tempEndPoint.Y));
((PictureBox)sender).Invalidate();
}
private void Picture_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button != MouseButtons.Left) return;
PictureBox org_pic = (PictureBox)(sender);
Point RecEndpoint=e.Location;
int xDown = Math.Min(RecStartpoint.X,RecEndpoint.X);
int yDown = Math.Min(RecStartpoint.Y, RecEndpoint.Y);
int xUp = Math.Max(RecStartpoint.X,RecEndpoint.X);
int yUp = Math.Max(RecStartpoint.Y,RecEndpoint.Y);
Rectangle rec = new Rectangle(xDown, yDown, Math.Abs(xUp - xDown), Math.Abs(yUp - yDown));
xDown = xDown * org_pic.Image.Width / org_pic.Width;
yDown = yDown * org_pic.Image.Height / org_pic.Height;
xUp = xUp * org_pic.Image.Width / org_pic.Width;
yUp = yUp * org_pic.Image.Height / org_pic.Height;
rectCropArea = new Rectangle(xDown, yDown, Math.Abs(xUp - xDown), Math.Abs(yUp - yDown));
pictureBox_preview_photo.Refresh();
Bitmap sourceBitmap = new Bitmap(org_pic.ImageLocation);
Graphics g = pictureBox_preview_photo.CreateGraphics();
g.DrawImage(sourceBitmap, new Rectangle(0, 0, pictureBox_preview_photo.Width, pictureBox_preview_photo.Height), rectCropArea, GraphicsUnit.Pixel);
}
I would try this approach:
First, make Image variable, in the scope of form
public partial class Form1 : Form
{
//variable for holding original image, before rectangle is drawn on it
Image originalImage = null;
public Form1()
{
InitializeComponent();
}
//rest of form's code...
second, save current picture in that variable on MouseDown
private void Picture_MouseDown(object sender, MouseEventArgs e)
{
//save it
startImage = ((PictureBox)sender).Image;
RecStartpoint = e.Location;
((PictureBox)sender).Invalidate();
}
lastly, on the end of MouseUp event, set Rectangle's width and height to zero and restore saved, original image
//snipped code
pictureBox_preview_photo.Refresh();
Bitmap sourceBitmap = new Bitmap(org_pic.ImageLocation);
Graphics g = pictureBox_preview_photo.CreateGraphics();
g.DrawImage(sourceBitmap, new Rectangle(0, 0, pictureBox_preview_photo.Width, pictureBox_preview_photo.Height), rectCropArea, GraphicsUnit.Pixel);
//make rectangle's widht and height 0 so that Paint event won't draw it
Rect.Width = Rect.Height = 0;
//restore image
this.Picture.Image = startImage;
I didn't understand that second question.

Using control functions in a bitmap in C#

I was thinking of implementing a bitmap into a picturebox (or the otherway round), such that I could have the option to:
1.drag and drop the item (Control function with mousebuttons)
2.rotate the item (bitmap function).
This is what I have currently:
Bitmap bmp = new Bitmap(#"my source");
PictureBox item = new System.Windows.Forms.PictureBox();
I create the picturebox on the click of a button:
private void button2_Click(object sender, EventArgs e)
{
item.BackColor = Color.Blue;
item.Location = new Point(400, 200);
item.MouseDown += new MouseEventHandler(textbox_MouseDown);
item.MouseMove += new MouseEventHandler(textbox_MouseMove);
item.MouseUp += new MouseEventHandler(textbox_MouseUp);
item.MouseWheel += new MouseEventHandler(textbox_MouseWheel);
item.Image = bmp;
item.SizeMode = PictureBoxSizeMode.StretchImage;
this.Controls.Add(item);
item.BringToFront();
}
and in the textbox_MouseMove void, I try to use the middle button to signal the rotation of the image
void textbox_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Middle )
{
if (activeControl == null || activeControl != sender)
{
return;
}
this.Paint += new PaintEventHandler(objectrotation_Paint);
Invalidate();
}
}
where the PaintEvent is responsible for the rotation of the image
private void objectrotation_Paint(object sender, PaintEventArgs d)
{
int dpi = 96;
bmp.SetResolution(dpi, dpi);
if (bmp != null)
{
float bw2 = bmp.Width / 2f;
float bh2 = bmp.Height / 2f;
d.Graphics.TranslateTransform(bw2, bh2);
d.Graphics.RotateTransform(angle);
d.Graphics.TranslateTransform(-bw2, -bh2);
d.Graphics.DrawImage(bmp,0,0);
d.Graphics.ResetTransform();
}
}
This however would create two sets of images, i.e. when I press button 2 I get one image, when I move my mouse with middle button down I get the second image (rotating).Refering to some of the questions on here, people recommend using
item.Image = bmp;
but it simply copies the from picturebox to the bitmap while they have seperate controls. While the picturebox class could not perform rotations without implementing a Bitmap, the Bitmap class does not have the option to perform actions like OnMouseMove etc.
Is there any way to combine my bitmap and the picturebox such that I could achieve my two goals?

Capturing screen properly works only in certain taskbar status

I'm working on a program loading an image or capturing a screen area and convert them to simulate color blinds' vision.
The problem I've encountered now is that capturing algorithm doesn't work in different taskbar status that I wrote the code in.
The taskbar of my computer is set up to the top of the screen, and it's locked. I wrote the code in that status, and I realized that the program doesn't work on other computers with different taskbar status. I unlocked it or moved it to the other sides of the screen and it didn't work in the way as I wanted.
To capture a screen area, an opaque form is opened by the main one, and area to be captured is calculated from the position of mouse when its left button is pressed and released.
Also the position of mouse is shown by a label keeping following the cursor while it is hovering on the form. The label stops following the cursor while I'm pressing the left button.
I have no ides why it works like this.. Does any part of my code is affected by taskbar status? Appreciate in advance! The code is copied below.
public partial class Form_Capture_Rect : Form
{
//CaptureRectangular is the name of this form
private void CaptureRectangular_Load(object sender, EventArgs e)
{
int width = Screen.PrimaryScreen.Bounds.Width;
int height = Screen.PrimaryScreen.Bounds.Height;
this.FormBorderStyle = FormBorderStyle.None;
this.Size = new System.Drawing.Size(width, height);
Message_Capture.Left = (width - Message_Capture.Width) / 2;
Message_Capture.Location = new System.Drawing.Point((width - Message_Capture.Width) / 2, (height - Message_Capture.Height) / 2);
}
//src: position the left button of mouse is pressed
//dest: position it is released
//leftTop: gets smaller value from src and dest, X and Y respectively
//width, height: size of the captured image
int srcX, srcY;
int destX, destY;
int leftTopX, leftTopY;
int width, height;
//gets position of mouse when its left button is pressed
private void Form_Capture_MouseDown(object sender, MouseEventArgs e)
{
srcX = Cursor.Position.X;
srcY = Cursor.Position.Y;
//this.WindowState = FormWindowState.Minimized;
}
private void Form_Capture_MouseUp(object sender, MouseEventArgs e)
{
//the captured image will be shown onto a picturebox 'Pic_Unchanged' of the main form
Form_Main mainForm = Application.OpenForms["Form_Main"] as Form_Main;
PictureBox Pic_Unchanged = mainForm.Controls["Pic_Unchanged"] as PictureBox;
//gets the position of mouse when it's released
destX = Cursor.Position.X;
destY = Cursor.Position.Y;
//when its width or height is zero, the function is terminated
if (srcX == destX || srcY == destY)
{
mainForm.WindowState = FormWindowState.Normal;
this.WindowState = FormWindowState.Minimized;
this.Close();
}
else
{
//calculate out these for values to get image
leftTopX = srcX < destX ? srcX : destX;
leftTopY = srcY < destY ? srcY : destY;
width = srcX < destX ? destX - srcX : srcX - destX;
height = srcY < destY ? destY - srcY : srcY - destY;
Graphics myGraphics = this.CreateGraphics();
Bitmap memoryImage = new Bitmap(width, height, myGraphics);
Graphics memoryGraphics = Graphics.FromImage(memoryImage);
//copies image
mainForm.WindowState = FormWindowState.Normal;
this.WindowState = FormWindowState.Minimized;//whithout this, the form will be captured
memoryGraphics.CopyFromScreen(leftTopX, leftTopY, 0, 0, new Size(width, height));
//show the captured image onto the picturebox
Pic_Unchanged.Image = memoryImage;
this.Close();
}
}
//shows the position of mouse with a label following cursor
//MouseLoc is a label
private void Form_Capture_Rect_MouseMove(object sender, MouseEventArgs e)
{
MouseLoc.Location = new System.Drawing.Point(Cursor.Position.X, Cursor.Position.Y);
MouseLoc.Text = e.X + ", " + e.Y;
}
//Delete a text 'Message_Capture' which says "Capture Area" 2.5 seconds after the form is shown up
private void DeleteMessage_Tick(object sender, EventArgs e)
{
Message_Capture.Visible = false;
}
}

I'm trying to show the current image in the pictureBox and stretch it but it's not showing anything why?

In For1 i have this code:
private void timer1_Tick(object sender, EventArgs e)
{
try
{
this.pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox1.Load(file_array_satellite[file_indxs_satellite]);
file_indxs_satellite = file_indxs_satellite - 1;
if (file_indxs_satellite < 0)
{
file_indxs_satellite = file_array_satellite.Length - 1;
}
}
catch
{
timer1.Enabled = false;
}
}
private void satellitesToolStripMenuItem_Click(object sender, EventArgs e)
{
file_array_satellite = Directory.GetFiles(UrlsPath, "RainImage*.*");
if (file_array_satellite.Length > 0)
{
DateTime[] creationTimes8 = new DateTime[file_array_satellite.Length];
for (int i = 0; i < file_array_satellite.Length; i++)
creationTimes8[i] = new FileInfo(file_array_satellite[i]).CreationTime;
Array.Sort(creationTimes8, file_array_satellite);
file_indxs_satellite = 0;
file_indxs_satellite = file_array_satellite.Length - 1;
timer1.Enabled = true;
}
}
private void pictureBox1_MouseEnter(object sender, EventArgs e)
{
this.pictureBox1.Size = new Size(500, 500);
pictureBox1.Location = new Point(this.Bounds.Width / 2,
this.Bounds.Height / 2);
this.pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox1.BringToFront();
}
private void pictureBox1_MouseLeave(object sender, EventArgs e)
{
this.pictureBox1.Size = new Size(100, 100);
pictureBox1.Location = new Point(12,
27);
}
In the original the picturebox1 size is 100x100 and each image i stretch to fit in the pictureBox.
When it's 100x100 everything is ok i see the animation of each image in the pictureBox.
Now i did an event that when i enter with the mouse to the pictureBox area it should move to the center of the form resize to 500x500 stretch the images and show the same animation.
And when i leave the pictureBox area it should return to it's original size and location.
When i enter with the mouse to the pictureBox1 area the pictureBox just vanish i don't see it anywhere once i leave the pictureBox area i see it 100x100 in it's original place and size.
Why when i enter with the mouse to the pictureBox1 area it's vanish i don't see it in the center of the form on size 500x500 ?
file_array_satellite is string[] and file_indxs_satellite is int.
RainImage*.* are the files names on the hard disk after downloaded them.
The idea is not to convert/change the files sizes on the hard disk each time i enter or leave so i wanted that once i enter the pictureBox1 area it will stretch the current image in the pictureBox and show it . It's working when it's 100x100 but not on 500x500.
When you mouse over the PictureBox and move it to the center of the form, you are moving it out from under the mouse cursor. This causes the MouseLeave event to immediately trigger, which places it back under your mouse cursor again, which causes the MouseEnter event to trigger again, etc.
You can do something like this:
bool suppressMouseLeave;
private void pictureBox1_MouseEnter(object sender, EventArgs e)
{
suppressMouseLeave = true;
this.pictureBox1.Size = new Size(500, 500);
pictureBox1.Location = new Point(this.Bounds.Width / 2,
this.Bounds.Height / 2);
this.pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox1.BringToFront();
//point the cursor to the new Position so that it's still kept on the pictureBox1
//This is important because it makes your idea acceptable.
//Otherwise you have to move your mouse onto your pictureBox and leave the
//mouse from it then to restore the pictureBox
Cursor.Position = PointToScreen(new Point(pictureBox1.Left + 250, pictureBox1.Top + 250));
suppressMouseLeave = false;
}
private void pictureBox1_MouseLeave(object sender, EventArgs e)
{
if(suppressMouseLeave) return;
this.pictureBox1.Size = new Size(100, 100);
pictureBox1.Location = new Point(12, 27);
}
I would venture a guess that this.Bounds.Width and this.Bounds.Height are not what you expect them to be, so the PictureBox isn't vanishing, you are just setting it to some location that is offscreen/off your form. Run Visual Studio in Debug mode and put a breakpoint around that line and see what this.Bounds is equal to. This may give you a clue as to the proper location you need to set.
How about in "in place" zoom like this?
private void pictureBox1_MouseEnter(object sender, EventArgs e)
{
Rectangle rc = pictureBox1.Bounds;
rc.Inflate(200, 200);
pictureBox1.Bounds = rc;
pictureBox1.BringToFront();
}
private void pictureBox1_MouseLeave(object sender, EventArgs e)
{
Rectangle rc = pictureBox1.Bounds;
rc.Inflate(-200, -200);
pictureBox1.Bounds = rc;
}

Categories