1

C# 中的这种行为很奇怪。我有以下课程可以让我有效地在桌面上“绘图”:

class drawOnDesktop {
    public static Form dodF = new Form();
    public static Graphics formGraphics;

    public drawOnDesktop() {
        formGraphics = dodF.CreateGraphics();
        dodF.BackColor = Color.LightGreen;
        dodF.TransparencyKey = Color.LightGreen;
        dodF.Size = new Size(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
        dodF.Location = new Point(0,0);
        dodF.StartPosition = FormStartPosition.Manual;
        //dodF.FormBorderStyle = FormBorderStyle.None;
        dodF.WindowState = FormWindowState.Maximized;
        dodF.MinimizeBox = false;
        dodF.MaximizeBox = false;
        dodF.ControlBox = false;
        //dodF.TopMost = true;  //For development in case something goes wrong
        dodF.BringToFront();
        dodF.Show();
    }

    public static void drawCircle(Point location) {
        formGraphics.FillEllipse(Brushes.Black, location.X, location.Y, 10, 10);
    }       
}

我这样称呼它,从我的主要形式:

drawOnDesktop dod = new drawOnDesktop();
drawOnDesktop.drawCircle(new Point(100,100));

如果您运行该代码,您会在屏幕的左上角看到一个黑色的小圆圈。问题是您可以看到表单的边框。现在,尝试注释掉该FormBorderStyle行。黑点会出现几分之一秒,然后消失。为什么!?如您所见,我在此表单上设置了很多属性,但它仍然无法正常工作。它是否被操作系统重新粉刷?

我不需要担心鼠标事件或类似的事情 - 放置在屏幕上的点完全是程序化的,而不是来自用户。同样,如果我设置dodF.ShowInTaskbar = false,整个程序都会崩溃。

如何修复此代码以使点出现并一直保留到 I formGraphics.Clear(Color.Black)

4

1 回答 1

1

不要在周围保留图形的副本,那只是自找麻烦。正如其他人所说,您应该使用paint事件在屏幕上绘制:

class drawOnDesktop
{
    public Form dodF = new Form();
    List<Point> circles = new List<Point>();
    public drawOnDesktop()
    {

        dodF.BackColor = Color.LightGreen;
        dodF.TransparencyKey = Color.LightGreen;
        dodF.Size = new Size(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
        dodF.Location = new Point(0, 0);
        dodF.StartPosition = FormStartPosition.Manual;
        dodF.FormBorderStyle = FormBorderStyle.None;
        dodF.WindowState = FormWindowState.Maximized;
        dodF.MinimizeBox = false;
        dodF.MaximizeBox = false;
        dodF.ControlBox = false;
        dodF.TopMost = true;  //For development in case something goes wrong
        dodF.BringToFront();
        dodF.Paint += dodF_Paint;
        dodF.Show();
    }

    void dodF_Paint(object sender, PaintEventArgs e)
    {
        using (Graphics g = dodF.CreateGraphics())
        {
            foreach(Point location in circles)
                g.FillEllipse(Brushes.Black, location.X, location.Y, 10, 10);    
        }
    }

    public  void drawCircle(Point location)
    {
        circles.Add(location);
    }
}

你可以用同样的方式调用它,但是现在每次重新绘制表单时,它都会重新绘制圆圈。

于 2012-11-10T19:58:48.260 回答