Sorry for my english. This is the first time I write a question in this language. I will be glad if you correct my grammatical errors.
I create a changing_button
and set its BackgroundImage property. I wanted this image to change when cursor is over this button. I made two pictures for that.
blue_image.png: enter image description here
red_image.png: enter image description here
Normally changing_button
should display red_image. But if cursor is over this button, it should display blue_image. The problem is that blue_image shifts when I try to override BackgroundImage property: enter image description here
How can I fix this?
using System;
using System.Drawing;
using System.Windows.Forms;
namespace winforms_test_1
{
public partial class Form1 : Form
{
Button changing_button;
Image blue_image = Image.FromFile("D://images//blue_image.png");
Image red_image = Image.FromFile("D://images//red_image.png");
public Form1()
{
InitializeComponent();
TableLayoutPanel main_panel = new TableLayoutPanel
{
BackColor = Color.White,
Dock = DockStyle.Fill
};
changing_button = new Button
{
BackgroundImage = red_image,
BackgroundImageLayout = ImageLayout.Center,
FlatStyle = FlatStyle.Flat,
Margin = new Padding(0, 0, 0, 0),
Size = new Size(50, 50),
};
changing_button.FlatAppearance.BorderSize = 0;
changing_button.MouseEnter = new System.EventHandler(this.test_button_MouseEnter);
changing_button.MouseLeave = new System.EventHandler(this.test_button_MouseLeave);
main_panel.Controls.Add(changing_button, 0, 0);
Controls.Add(main_panel);
}
void test_button_MouseEnter(object sender, EventArgs e)
{
changing_button.Image = blue_image;
}
void test_button_MouseLeave(object sender, EventArgs e)
{
changing_button.Image = red_image;
}
}
}
CodePudding user response:
Instead of changing the background image, set the initial Image to the red image. BackgroundImage and Image look like they have slightly different positions.
changing_button = new Button
{
Image = red_image,
ImageLayout = ImageLayout.Center,
FlatStyle = FlatStyle.Flat,
Margin = new Padding(0, 0, 0, 0),
Size = new Size(50, 50),
};
Use either BackgroundImage or Image, but not both.