开发者

Drawing C# graphics without using Windows Forms

Could someone provide an example for drawing graphics without using Windows Forms? I have an app that doesn't have a console window or Windows form, but i 开发者_JAVA百科need to draw some basic graphics (lines and rectangles etc.)

Hope that makes sense.


This should give you a good start:

  [TestFixture]
  public class DesktopDrawingTests {
    private const int DCX_WINDOW = 0x00000001;
    private const int DCX_CACHE = 0x00000002;
    private const int DCX_LOCKWINDOWUPDATE = 0x00000400;

    [DllImport("user32.dll")]
    private static extern IntPtr GetDesktopWindow();

    [DllImport("user32.dll")]
    private static extern IntPtr GetDCEx(IntPtr hwnd, IntPtr hrgn, uint flags);

    [Test]
    public void TestDrawingOnDesktop() {
      IntPtr hdc = GetDCEx(GetDesktopWindow(),
                           IntPtr.Zero,
                           DCX_WINDOW | DCX_CACHE | DCX_LOCKWINDOWUPDATE);

      using (Graphics g = Graphics.FromHdc(hdc)) {
        g.FillEllipse(Brushes.Red, 0, 0, 400, 400);
      }
    }
  }


Something like this?

 using System.Drawing;

 Bitmap bmp = new Bitmap(200, 100);
 Graphics g = Graphics.FromImage(bmp);
 g.DrawLine(Pens.Black, 10, 10, 180, 80);


The question is a little unfocused. Specifically - where do you want to draw the lines and rectangles? Generally speaking, you need a drawing surface, usually provided by a windows form.

Where does the need to avoid windows forms come from?

Are you using another kind of window?

For a windows form you could use code similar to this:

namespace WindowsFormsApplication1 {
    public partial class Form1 : Form {
        public Form1() {
            InitializeComponent();
        }

        protected override void OnPaint(PaintEventArgs e) {
            base.OnPaint(e);

            e.Graphics.DrawLine(new Pen(Color.DarkGreen), 1,1, 3, 20 );
            e.Graphics.DrawRectangle(new Pen(Color.Black), 10, 10, 20, 32 );
        }
    }
}

You can generally do this with any object that lets you get a handle for a "Graphics" object (like a printer).


Right, the way i've done it is with a windows form, but make the background transparent, and then get rid of all the borders...

Thanks for the replys anyway..

J

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜