pictureBox,graphics和messageBox

时间:2013-08-15 18:47:11

标签: c# graphics picturebox messagebox

我对这些元素有些疑问。我尝试用图形绘制线条并将其放在pictureBox上。然后我调用MessageBox,它在我的mainWindow后面运行。因为我无法使用mainWindow,因为程序等待单击MesageBox的按钮。但我没有看到它。 Alt按钮只能帮我,或Alt + Tab,但它很愚蠢。所以,这是我的代码:

公共部分类Form1:表单     {         图形g;         位图btm;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        btm = new Bitmap(pictureBox1.Size.Width, pictureBox1.Size.Height);
        g = CreateGraphics();
        g = Graphics.FromImage(btm);
        Pen p = new Pen(Brushes.Red);
        g.DrawLine(p, 0, 0, btm.Size.Width, btm.Size.Height);            
        pictureBox1.Refresh();
        g.Dispose();
    }

    protected override void OnClosing(CancelEventArgs e)
    {
        DialogResult dr = MessageBox.Show("Exit?", "Exit", MessageBoxButtons.YesNo);
        if (dr == DialogResult.No) e.Cancel = true; else e.Cancel = false;
    }

    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        pictureBox1.Image = btm;
    }
}

告诉我,我的问题在哪里?感谢

1 个答案:

答案 0 :(得分:1)

刷新表单时,将调用paint事件。您可以通过设置标志来避免此时自定义绘图。

bool updatePictureBox = true;

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    if(updatePictureBox)
        pictureBox1.Image = btm;
}

protected override void OnClosing(CancelEventArgs e)
{
    updatePictureBox = false;
    DialogResult dr = MessageBox.Show(this,"Exit?", "Exit", MessageBoxButtons.YesNo);
    if (dr == DialogResult.No) e.Cancel = true; else e.Cancel = false;
}

但是,您可以通过在Paint事件本身内进行绘制来避免整个问题。我建议这样做,而不是使用上面的标志方法。

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    var g = e.Graphics;            
    using (Pen p = new Pen(Brushes.Red))
    {
        g.DrawLine(p, 0, 0, pictureBox1.Width, pictureBox1.Height);
    }
}