如何在C#WinForm中删除/删除/撤消DrawString

时间:2015-08-19 13:49:38

标签: c# winforms drawstring

我的表单有背景图片。我有一些PictureBoxes我用作按钮。我试图让MouseEnter / MouseLeave事件显示标签或pictureBox。

我一直在尝试各种方法。我得到了类似的结果 - 标签或图片框看起来不错,但在MouseLeave上,label1.Visible = false;在窗体的背景图像上生成一个非常临时的空白框。虽然它功能齐全,但它似乎只是一个非常小的延迟,但会使程序看起来很糟糕。

我尝试使用DrawString方法。这似乎是一个不错的选择,但我无法弄清楚如何删除MouseLeave事件上的对象。

这可能吗?如果没有,是否有更好的选择来完成我想要完成的任务?

以下是我绘制字符串的方法(在buttonClick事件中进行测试):

Graphics g = this.CreateGraphics();
string letter = "Yo Dawg!";
g.DrawString(letter, new Font(FontFamily.GenericSansSerif, 20, FontStyle.Regular),
new SolidBrush(Color.Black), 100, 100);

1 个答案:

答案 0 :(得分:4)

你会在paint事件中绘制,在MouseLeave设置一个标志,导致一个带有Invalidate()的绘画,然后在绘画内如果未设置标志则不绘制任何东西。

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();
    }
}
相关问题