1

My form has a background image. I have some pictureBoxes i am using as buttons. I am attempting to have a MouseEnter/MouseLeave event to display label or pictureBox.

I have been trying various approaches. I am getting similar results- The label or picturebox appears fine, but on MouseLeave, label1.Visible = false; causes a very temporary blank box over the background image of the form. While it is fully functional, it just seems like a very slight lag, but makes the program look bad.

I experimented with the DrawString method. This seems like it could be a good option, but i cannot figure out how to remove the object on a MouseLeave event.

Is this possible? If not, is there a better option to accomplish what i am trying to accomplish?

Here is how I am drawing my string (in buttonClick event for testing):

Graphics g = this.CreateGraphics();
string letter = "Yo Dawg!";
g.DrawString(letter, new Font(FontFamily.GenericSansSerif, 20, FontStyle.Regular),
new SolidBrush(Color.Black), 100, 100);
Vishal Suthar
  • 17,013
  • 3
  • 59
  • 105
HoustoneD
  • 63
  • 1
  • 3
  • 15

1 Answers1

4

You would draw in the paint event, in MouseLeave set a flag, cause a paint with Invalidate() then within paint if the flag is not set don't draw anything.

public partial class TheForm : Form
{
    private Font _font = new Font(FontFamily.GenericSansSerif, 20, FontStyle.Regular);
    private bool _hovering = false;

    public TheForm() {
        InitializeComponent();

        picBox.Paint += new PaintEventHandler(picBox_Paint);
        picBox.MouseEnter += (sender, e) => UpdateText(true);
        picBox.MouseLeave += (sender, e) => UpdateText(false);
    }

    private void picBox_Paint(object sender, PaintEventArgs e) {
        if (_hovering)
            e.Graphics.DrawString("Yo Dawg!", _font, Brushes.Black, 100, 100);
    }

    private void UpdateText(bool show) {
        _hovering = show;
        picBox.Invalidate();
    }
}
Alex K.
  • 171,639
  • 30
  • 264
  • 288
  • 2
    This solution works perfectly. Thank you kindly, good sir. You are the man! – HoustoneD Aug 19 '15 at 14:35
  • Alex K- I have another question for you pertaining to this solution- i have several different strings that i will be drawing, depending on which button is hovered over, and all the "labels" will be in the same location (center screen). I have messed around with some different settings and cannot seem to find a way to make this work, as the topmost picturebox, even if empty and background set to transparent, blocks out all pictureboxes behind it. i tried having one picturebox and some if statements and couldnt get all the buttons to "share" one PB to draw strings in. Any ideas for this? – HoustoneD Aug 21 '15 at 02:10