使用System.Drawing.DrawRectangle绘制选择矩形以选择事物

时间:2014-02-09 13:46:34

标签: c# .net winforms drawing system.drawing

我有一个Windows窗体应用程序,需要能够在窗体上选择对象,就像通过左键单击并拖动文件一样选择桌面上的文件,如下所示:

enter image description here

我有以下代码,我自己写的,但是很糟糕。这是不对的。我现在不太担心它的“选择”部分,我主要关心的是我如何画这样的?

private void splitContainer1_Panel1_MouseMove(object sender, MouseEventArgs e)
{
    if (mouseDown)
    {
        // TODO: Draw Rectangle (so you can select elements on the canvas).


        Graphics graphics = Graphics.FromHwnd(splitContainer1.Panel1.Handle);
        graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;

        Pen pen = new Pen(Color.SlateBlue, 0.5f);

        graphics.PageUnit = GraphicsUnit.Pixel;

        graphics.DrawRectangle(pen, e.X, e.Y, (e.Location.X + e.X) - lastCursorLocation.X, (e.Location.Y + e.Y) - lastCursorLocation.Y);
    }
}

更新

private void splitContainer1_Panel1_Paint(object sender,PaintEventArgs e)         {                 // TODO:绘制矩形(这样你就可以在画布上选择元素了。)

        Graphics graphics = Graphics.FromHwnd(splitContainer1.Panel1.Handle);
        graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;

        Pen pen = new Pen(Color.SlateBlue, 0.5f);

        graphics.PageUnit = GraphicsUnit.Pixel;

        graphics.DrawRectangle(pen, 1, 1, 1, 1);

        Invalidate();
    }

将代码放在Paint事件中并调用Invalidate()后,根本没有任何内容绘制。我显然做错了什么,但是什么?

2 个答案:

答案 0 :(得分:0)

检查以下主题。您正在寻找的是rubber band

<强> filled rubber band in Winforms Application

答案 1 :(得分:0)

我最终使用了一些我在Microsoft Connect网站上找到的代码:

http://support.microsoft.com/kb/314945