Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
553 views
in Technique[技术] by (71.8m points)

c# - Trouble Getting System.Drawing.Graphics to work in Form

I am trying to make a C# Windows form in Visual Studio so I can draw on the form (like a basic version of Microsoft Paint). I am working through an example in a C# 2012 book. I have written the code verbatim, but when I build and run the program, I cannot actually draw anything on the form. The code compiles successfully without any errors. Can anyone see where the code can be improved so that I can successfully draw on the form?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace paint3
{
public partial class Form1 : Form
{
    bool shouldPaint = false;

    public Form1()  // constructor
    {
        InitializeComponent();
    }

    private void Form1_MouseDown(object sender, MouseEventArgs e)
    {
        shouldPaint = true;
    }

    private void Form1_MouseUp(object sender, MouseEventArgs e)
    {
        shouldPaint = false;
    }

    private void Form1_MouseMove(object sender, MouseEventArgs e)
    {
        if (shouldPaint)
        {
            using (Graphics graphics = CreateGraphics())
            {
                graphics.FillEllipse(new SolidBrush(Color.BlueViolet), e.X, e.Y, 4, 4);
            }
        }
    }
}
}

As far as Form1 is concerned, it's simply a blank form that is created when I click "New Windows Forms Application" in Visual Studio 2012. I haven't added any buttons, text boxes, or other controls to Form1.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try the paint events for drawing. this will help you. The link is just an example. you need to implement as per the requirements


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...