I'm having a rather irritating problem with images on buttons in .NET. They don't behave as you would expect an image on a button to behave.
In the properties of a button you can set Image. So I select an image and the image shows up on the button! So far so good.
When a button is clicked, or in a pressed state, the text of the button will move down and right one pixel to create a depth. But not the image! It will stay in the same position, and it will look weird.
There is also the BackgroundImage property, but that's even worse! Because if I set BackgroundImageLayout to None instead of Center, the image will move up and left when pressed, the complete opposite direction of the text! What's up with that?
Anyway, what I want to achieve is a button image that moves just like the text would move when the button is in a pressed state. Is there a way to do this?
Just make a new image and paste the original one at an offset. Then set that as the Button's Image.
Example:
private void button1_MouseDown(object sender, MouseEventArgs e)
{
// replace "button_image.png" with the filename of the image you are using
Image normalImage = Image.FromFile("button_image.png");
Image mouseDownImage = new Bitmap(normalImage.Width + 1, normalImage.Height + 1);
Graphics g = Graphics.FromImage(mouseDownImage);
// this will draw the normal image at an offset on mouseDownImage
g.DrawImage(normalImage, 1, 1); // offset is one pixel each for x and y
// clean up
g.Dispose();
button1.Image = mouseDownImage;
}
private void button1_MouseUp(object sender, MouseEventArgs e)
{
// reset image to the normal one
button1.Image = Image.FromFile("button_image.png");
}
EDIT: The following function fixes a problem where the image would not 'pop' back up when the cursor leaves the button area while the mouse button is still pressed (see Labor's comment below):
private void button1_MouseMove(object sender, MouseEventArgs e)
{
Point relMousePos = e.Location;
bool mouseOverButton = true;
mouseOverButton &= relMousePos.X > 0;
mouseOverButton &= relMousePos.X < button1.Width;
mouseOverButton &= relMousePos.Y > 0;
mouseOverButton &= relMousePos.Y < button1.Height;
if (mouseOverButton != MouseButtons.None)
{
button1_MouseDown(sender, e);
}
else
{
button1_MouseUp(sender, e);
}
}
Related
I am working on real-time video processing project.
During the real-time video i need to get mouse position when left clicked. To do that i have one button to send mouse position to text boxes. To see position of the cursor, i have two text boxes named as txt4 and txt5 for X and Y position seperately.
I have written the given code as shown the below. When i click the button it shows the current postion of the mouse (actually it is the position of the button) but then when i do left click position of the mouse is not shown in the text boxes. Position is shown when i press "Enter" while button is clicked.
What is wrong? and How can i correct it?
private void btnCursor_Click(object sender, EventArgs e)
{
if (device.IsRunning)
{
this.Cursor = new Cursor(Cursor.Current.Handle);
txt4.Text = string.Format("x={0:0000}", Cursor.Position.X);
txt5.Text = string.Format("y={0:0000}", Cursor.Position.Y);
}
}
private void panel1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Click>0)
{
txt4.Text = MousePosition.X.ToString();
txt5.Text = MousePosition.Y.ToString();
}
}
I tried to get mouse position when i do left click.
What i get is mouse position when i pressed "Enter" instead of left clicked.
I have error in line "if(e.Click>0)".
So I'm trying to make a slider. I'm using my cursor to move a button's x position.
I have 3 functions, the mouseDown, mouseUp and the mouseMove function. In the mouseUp and mouseDown functions I set a variable to true and false to tell the program that the mouse is clicked or not. In the mouseMove function I tell the program to set the button's x position to the x position of the mouse when the mouse is clicked. This works but has 2 problems.
The first problem is that when I press the button and move it, the button moves along with the mouse's x but it has a space between the mouse and the button. It looks a bit like this:
CURSOR.......BUTTON
The space between the cursor and button change when I change the resolution of the form.
The second problem is that when I move the button it flickers a bit. It only does this at higher speeds but it is a problem in my case.
My code looks like this:
bool mouseDown = false;
private void volumeGrabBT_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
mouseDown = true;
}
}
private void volumeGrabBT_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
mouseDown = false;
}
}
private void volumeGrabBT_MouseMove(object sender, MouseEventArgs e)
{
if (mouseDown == true)
{
Point volumeBTPoint = new Point();
volumeBTPoint.X = Cursor.Position.X;
volumeBTPoint.Y = volumeGrabBT.Location.Y;
volumeGrabBT.Location = volumeBTPoint;
}
}
The volumeGrabBT is the button I'm trying to move along with the mouse.
The volumeBTPoint is the point of the button I'm trying to set the button's position to.
I hope someone can help me fix these problems. Thanks in advance!
I believe that flickering can be fixed by setting some additional form styles: SetStyle(ControlStyles.AllPaintingInWmPaint |ControlStyles.UserPaint | ControlStyles.DoubleBuffer, true);
in form's constructor. It will use double buffering and generally just draws faster.
For the Cursor class, it's relative to the screen, not your form. You can use this.PointToClient() function to get client's space position of cursor, like this:
Point clientCursor = this.PointToClient(Cursor.Position);
and then use clientCursor to get exact X in your client space.
You have to translate screen coordinates to client coordinates.
Point volumeBTPoint = new Point();
Point point = this.PointToClient(Cursor.Position);
volumeBTPoint.X = point.X;
volumeBTPoint.Y = volumeGrabBT.Location.Y;
volumeGrabBT.Location = volumeBTPoint;
Instead of this you should use button's parent control (Panel, GroupBox, etc).
I have to make a windows form in C# where two PictureBox are overlapping. TopPictureBox is containing a transparent png picture. By default TopPictureBox can be clicked by clicking any visible or transparent area of the image in TopPictureBox. But I want to make that TopPictureBox only can be clicked by clicking visible area of image, not in transparent area. Also I want to make that cursor will only change on the visible area of the image, not in transparent area.
IS THERE ANY WAY TO DO THESE?
I am using this code to make TopPictureBox transparent.
TopPictureBox.BackColor = Color.Transparent;
Thank You for Help.
Checking if a position in PictureBox is Transparent or not depends on the Image and SizeMode property of PictureBox.
You can not simply use GetPixel of Bitmap because the image location and size is different based on SizeMode. You should first detect the size and location of Image based on SizeMode:
public bool HitTest(PictureBox control, int x, int y)
{
var result = false;
if (control.Image == null)
return result;
var method = typeof(PictureBox).GetMethod("ImageRectangleFromSizeMode",
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
var r = (Rectangle)method.Invoke(control, new object[] { control.SizeMode });
using (var bm = new Bitmap(r.Width, r.Height))
{
using (var g = Graphics.FromImage(bm))
g.DrawImage(control.Image, 0, 0, r.Width, r.Height);
if (r.Contains(x, y) && bm.GetPixel(x - r.X, y - r.Y).A != 0)
result = true;
}
return result;
}
Then you can simply use HitTest method to check if the mouse is over a non-transparent area of PictureBox:
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (HitTest(pictureBox1,e.X, e.Y))
pictureBox1.Cursor = Cursors.Hand;
else
pictureBox1.Cursor = Cursors.Default;
}
private void pictureBox1_MouseClick(object sender, MouseEventArgs e)
{
if (HitTest(pictureBox1, e.X, e.Y))
MessageBox.Show("Clicked on Image");
}
Also setting BackColor to Color.Transparent only makes the PictureBox transparent relative to it's parent. For example if you have 2 PictureBox in a Form setting the transparent back color, just cause you see the background of form. To make a PictureBox which supports transparent background, you should draw what is behind the control yourself. You can find a TransparentPictureBox in this post: How to make two transparent layer with c#?
One way is to check whether the colour of the pixel where the user clicked, is the same as the background colour of the form. If yes, then the user clicked on a transparent area.
(Note : As Reza mentioned, this code can be used only when there are no overlapping PictureBoxes, i.e. only when the transparent area of the image is of the same colour as the Form's background)
Color pixelColour;
private void myPicturebox_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
pixelColour = ((Bitmap)myPicturebox.Image).GetPixel(point.X, point.Y);
if (this.BackColor == pixelColour)
{
// User clicked on transparent area
}
else
{
// User clicked on image
}
}
}
How can I clear the fill of a rectangle? I only want to keep the border.
g.FillRectangle(Brushes.Transparent, x, y, w, h);
Didn't work, neither did aRGB with alpha, I want to delete the fill so there's only the border left.
So what you want is
g.DrawRectangle(Pens.Black,x,y,w,h);
I think
EDIT: due to a change in the OP requirements this is not exactly the answer he wants, though it is not incorrect, therefore I choose to leave it here, for now.
you must set new clip for your graphics after set clip clear it, then restore clip to normal.
g.SetClip(new Rectangle(x,y,w,h), CombineMode.Replace);
g.Clear(Color.Transparent);
Ok so you are after a selection tool, you might have wanted to tell us that in the first place.
Create a new windows form application.
in the form events use mousedown, mouseup and mousemove
public Point MouseXY = new Point(0, 0);
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
MouseXY = e.Location;
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
int width = e.Location.X - MouseXY.X;
int height = e.Location.Y-MouseXY.Y;
this.Refresh();
CreateGraphics().DrawRectangle(Pens.Blue, new Rectangle(MouseXY, new Size(width,height)));
}
}
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
this.Refresh();
}
This code is not perfect and I don't pretend it is. What this will do is draw a blue rectangle that starts where you click and follows your mouse. It does not draw a negative rectangle, you would have to determine whether your mouse is currently to the left or up from your starting point then draw the rectangle accordingly, but I think you can figure that out on your own. as well the rectangle is not persistent, though I do not believe you would want it to be.
I have a problem:
I have 3 picture boxes with 3 different images as in Image
what can i set to pictureBox3 so both images look same.....
EDITED:
I want to move pictureBox3 on pictureBox2,
So there is no Option to merge them to single image
Make sure the image in pictureBox3 is transparent. Set the BackColor to transparent. In code, set the Parent property of the pictureBox3 to be pictureBox2. Adjust the Location coordinates of pictureBox3 since they will be relative to the coordinates of pictureBox2 once you've changed the Parent.
private void Form1_Load(object sender, EventArgs e)
{
pictureBox3.Parent = pictureBox2;
pictureBox3.Location =
new Point(
pictureBox3.Location.X
- pictureBox2.Location.X,
pictureBox3.Location.Y
- pictureBox2.Location.Y);
}
In designer you will not see the transparency, but at runtime you will.
Update
In the image, the left side shows the designer view, the right side is the runtime version.
Another update
I really don't understand how it would be possible that this doesn't work for you. I suppose there must be something we are doing different. I'll describe the exact steps to take to create a working sample. If you follow the exact same steps, I wonder if we'll get the same results or not. Next steps describe what to do and use two images I found on the net.
Using Visual Studio 2008, create a New Project using template Windows Forms Application. Make sure the project is targeted at the .NET Framework 3.5.
Set the Size of the Form to 457;483.
Drag a PictureBox control onto the form. Set its Location to 0;0 and its Size to 449;449.
Click the ellipsis besides its Image property, click the Import... button and import the image at http://a.dryicons.com/files/graphics_previews/retro_blue_background.jpg (just type the URL in the File name text box and click Open). Then click OK to use the image.
Drag another PictureBox onto the form, set its Location to 0;0 and its Size to 256;256. Also set its BackColor property to Transparent.
Using the same method as described above, import image http://www.axdn.com/redist/axiw_i.png which is a transparent image.
Now place the following code in the form's OnLoad event handler:
private void Form1_Load(object sender, EventArgs e)
{
pictureBox2.Parent = pictureBox1;
}
That's it! If I run this program I get a transparent image on top of another image.
I'll add another example that according to the updated requirement allows for moving image3.
To get it working, put an image with transparency in Resources\transp.png
This uses the same image for all three images, but you can simply replace transparentImg for image1 and image2 to suitable images.
Once the demo is started the middle image can be dragged-dropped around the form.
public partial class Form1 : Form
{
private readonly Image transparentImg; // The transparent image
private bool isMoving = false; // true while dragging the image
private Point movingPicturePosition = new Point(80, 20); // the position of the moving image
private Point offset; // mouse position inside the moving image while dragging
public Form1()
{
InitializeComponent();
//
// pictureBox1
//
this.pictureBox1.Location = new System.Drawing.Point(0, 0);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(231, 235);
this.pictureBox1.TabIndex = 0;
this.pictureBox1.TabStop = false;
this.pictureBox1.Paint += new System.Windows.Forms.PaintEventHandler(this.pictureBox1_Paint);
this.pictureBox1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.pictureBox1_MouseDown);
this.pictureBox1.MouseMove += new System.Windows.Forms.MouseEventHandler(this.pictureBox1_MouseMove);
this.pictureBox1.MouseUp += new System.Windows.Forms.MouseEventHandler(this.pictureBox1_MouseUp);
this.Controls.Add(this.pictureBox1);
transparentImg = Image.FromFile("..\\..\\Resources\\transp.png");
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
var g = e.Graphics;
g.DrawImageUnscaled(transparentImg, new Point(20, 20)); // image1
g.DrawImageUnscaled(transparentImg, new Point(140, 20)); // image2
g.DrawImageUnscaled(transparentImg, movingPicturePosition); // image3
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
var r = new Rectangle(movingPicturePosition, transparentImg.Size);
if (r.Contains(e.Location))
{
isMoving = true;
offset = new Point(movingPicturePosition.X - e.X, movingPicturePosition.Y - e.Y);
}
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (isMoving)
{
movingPicturePosition = e.Location;
movingPicturePosition.Offset(offset);
pictureBox1.Invalidate();
}
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
isMoving = false;
}
}
This code will do the trick:
using (Graphics g = Graphics.FromImage(pictureBox1.Image))
{
g.DrawImage(pictureBox2.Image,
(int)((pictureBox1.Image.Width - pictureBox2.Image.Width) / 2),
(int)((pictureBox1.Image.Height - pictureBox2.Image.Height) / 2));
g.Save();
pictureBox1.Refresh();
}
It will draw the image from pictureBox2 on the existing image of pictureBox1.
For starters, set the BackColor property of PictureBox3 to Transparent. This should work in almost all cases.
You should also use an image with a transparent background instead of white so you do not have the white borders around your purple circle. (Recommended image format: PNG)
Update
Following the replies I got, it appears setting the BackColor to Transparent doesn't work. In that case, it's best you handle the Paint event of the PictureBox and do the painting of the new image yourself as Albin suggested.
You might do some hack by overriding OnPaint and stuff, example here.
But I'd recommend to merge the pictures in pictureBox2 and 3 into a single image before displaying them in a single pictureBox.