【问题标题】:Draw a rectangle in a panel of a form when a button click event is fired from another form当从另一个窗体触发按钮单击事件时,在窗体的面板中绘制一个矩形
【发布时间】:2018-06-15 19:41:07
【问题描述】:

我目前正在开发有两个表单的 Windows 表单应用程序;表格 1 和表格 2。 form1 中有一个按钮,单击时会打开 form2,我想要的是在单击 Form2 中的按钮时在 form1 的面板内创建一个矩形。我在form2的按钮单击事件中放置了一些代码来创建矩形,但是单击时没有显示任何内容。但是,每当我将 draw.rectangle 方法放在单击按钮的同一个表单中时,它都会起作用,但不同的是它不会

这是form1里面的代码

  private void btnSave_Click(object sender, EventArgs e)
    {
        Layoutsetting a = new Layoutsetting();
        a.ShowDialog();
    }
public void DrawObject()
    {

            Graphics g = panel1.CreateGraphics();
            Rectangle rect = new Rectangle(10, 10, 80, 90);
            rect.Inflate(-10, -10);
            g.DrawRectangle(black, rect);
            g.FillRectangle(Brushes.BlueViolet, rect);
            StringFormat f = new StringFormat();
            f.LineAlignment = StringAlignment.Center;
            f.Alignment = StringAlignment.Center;
            g.DrawString("Hello", this.Font, Brushes.GhostWhite, rect, f);
            panel1.Refresh();
 }

这是form2里面的代码

  private void btnConfirm_Click(object sender, EventArgs e)
    {
        Form1.Default.DrawObject();
        this.Close();
    }

【问题讨论】:

  • 按钮中的“a”是否点击了这个神奇的表单2?您可以将自身的引用传递给新表单.. id 猜测“Form1.Default”不是您的想法
  • 在这一行:Form1.Default.DrawObject(); Default 到底是什么?
  • 如果要保持绘制的矩形,您需要在 Paint 事件中使用 e.Graphics 进行绘制。还有一个在某处定义的 Rectangle 和一个打开绘图的标志。然后你可以使面板无效,矩形将最小化表单。底线:永远不要使用CreateGraphics

标签: c#


【解决方案1】:

问题不在于绘制矩形,只要面板的最轻微部分被隐藏(例如,它的一部分在另一个表单后面)并重新绘制面板,面板绘制事件就会触发,因此矩形消失(但是当它是绘制事件不会触发的活动表单,矩形将被绘制并且不会被清除,除非您执行需要重绘面板的操作。)。

简单的解决方案:

创建一个recangle的图像并在需要时将其用作背景图像,而不是绘制它。

另一种解决方案:

向表单(或面板)添加属性:

public bool NeedsToBeDrawn {get; set;}

而不是这行代码:

Form1.Default.DrawObject();

只需将属性设置为 true:

   Form1.NeedsToBeDrawn  = true;

并将您的代码移动到面板的绘制事件中:

private void panel1_Paint(object sender, PaintEventArgs e)
{
     if(NeedsToBeDrawn)
     {
            Rectangle rect = new Rectangle(10, 10, 80, 90);
            rect.Inflate(-10, -10);
            e.Graphics.DrawRectangle(black, rect);
            e.Graphics.FillRectangle(Brushes.BlueViolet, rect);
            StringFormat f = new StringFormat();
            f.LineAlignment = StringAlignment.Center;
            f.Alignment = StringAlignment.Center;
            e.Graphics.DrawString("Hello", this.Font, Brushes.GhostWhite, rect, f);
     }
}

【讨论】:

    【解决方案2】:

    你必须给 Paint 添加一个方法:

    panel1.Paint += new System.Windows.Forms.PaintEventHandler(this.draw);
    
    private void draw(object sender, PaintEventArgs e)
    {
        if(buttonClicked) {
            Graphics g = e.Graphics;
            //...
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-19
      • 1970-01-01
      • 2011-11-23
      • 1970-01-01
      相关资源
      最近更新 更多