【问题标题】:Visual C# - Calling a function from a class does nothingVisual C# - 从类中调用函数什么都不做
【发布时间】:2016-12-10 23:29:51
【问题描述】:

我在尝试在面板上绘制矩形时遇到问题。我创建了一个具有执行此操作的函数的类,但是当我调用它时没有任何反应。当我使用函数中的代码而不是实际函数时,它可以工作。有任何想法吗?这是代码

    class Snake : Form1
    {
        public static int x = 20;
        public static int y = 20;
        public static int r = 20;

        public void Draw()
        {
            SolidBrush brush = new SolidBrush(Color.Green);
            Graphics G = panel1.CreateGraphics();
            G.FillRectangle(brush, x, y, r, r);
        }
    }

    //...

    private void panel1_MouseClick(object sender, MouseEventArgs e)
    {
        Snake s = new Snake();
        s.Draw();
    }

【问题讨论】:

  • 请澄清这部分问题的含义:“当我使用函数中的代码而不是实际函数时,它会起作用。”
  • 好吧,如果我让代码保持原样,当我点击面板时没有任何反应,但如果我写 SolidBrush Brush = new SolidBrush(Color.Green);图形 G = panel1.CreateGraphics(); G.FillRectangle(brush, x, y, r, r);而不是 Snake s = new Snake(); s.Draw();它有效。
  • 每次单击鼠标时,您都会创建一个新表单,该表单不会显示,因此它会立即超出范围并被垃圾收集。我猜您是在尝试在现有表单上调用 Draw 方法,而不是创建一个全新的表单?

标签: c# function class


【解决方案1】:

Snake 对象在其自己的图形上下文中进行绘制,这与您单击的面板的上下文不同。为了解决这个问题,面板必须为Draw函数提供图形:

class Snake
{
    public static int x = 20;
    public static int y = 20;
    public static int r = 20;

    public void Draw(Graphics G)
    {
        SolidBrush brush = new SolidBrush(Color.Green);
        G.FillRectangle(brush, x, y, r, r);
    }
}

//...

private void panel1_MouseClick(object sender, MouseEventArgs e)
{
    using (Graphics G = panel1.CreateGraphics())
    {
        Snake s = new Snake();
        s.Draw(G);
    }
}

在相关说明中,请确保始终处置 Graphics 对象。

【讨论】:

    【解决方案2】:

    实现 Panel Paint 事件:

    class Snake : Form1
    {
        public static int x = 20;
        public static int y = 20;
        public static int r = 20;
    
        public void Draw()
        {
          panel1.Refresh() ;
        }
    
         private void panel1_Paint(object sender, PaintEventArgs e)
         {
            SolidBrush brush = new SolidBrush(Color.Green);
            Graphics G = panel1.CreateGraphics();
            G.FillRectangle(brush, x, y, r, r);
         }
    

    }

    【讨论】:

      猜你喜欢
      • 2012-08-21
      • 1970-01-01
      • 1970-01-01
      • 2019-02-08
      • 1970-01-01
      • 2018-02-11
      • 2018-03-16
      • 2012-05-17
      • 1970-01-01
      相关资源
      最近更新 更多