Draw rectangle on button click in C#

懵懂的女人 提交于 2020-01-07 09:22:17

问题


I have form in which background is transparent. I have a button on the form. When I click the button, screenshot of the transparent area is taken and the screenshot is analyzed for a certain reference-image, and if the image is found, a rectangle should be drawn around the reference-image. For now nothing happens when I press the button. I'm using BotSuite Dll, provided here: http://www.botsuite.net/. I My code for the button click is as follows:

    private void button1_Click(object sender, EventArgs e)
    {
        Invalidate();
        //take screenshot of transparent form area
        Bitmap CapturedScreen = ScreenShot.Create((this.Left + 8), (this.Top + 30), 780, 415);
        ImageData refpic = new ImageData("pallo.bmp");
        ImageData source = new ImageData(CapturedScreen);
        Graphics graphics = this.CreateGraphics();
        Pen p = new Pen(Color.Black, 1);
        graphics.DrawRectangle(p, Template.Image(source, refpic, 100));
        Refresh();
    }

回答1:


Try moving the drawing logic to the Paint evet.

Let's assume you are drawing on a panel called pnl. Try the following:

On your constructor register to the paint evet:

 this.pnl.Paint += pnl_Paint;

Upon a click, set a flag to indicate that painting is required for the rectangle:

bool _paintRect;

private void button1_Click(object sender, EventArgs e)
{
    this._paintRect = true;
    Invalidate();        
    Refresh();
}

In the paint event handler, do the actual paint:

private void pnl_Paint(object sender, PaintEventArgs e)
{
   //take screenshot of transparent form area
    Bitmap CapturedScreen = ScreenShot.Create((this.Left + 8), (this.Top + 30), 780, 415);
    ImageData refpic = new ImageData("pallo.bmp");
    ImageData source = new ImageData(CapturedScreen);

    Graphics graphics = e.Graphics;

    Pen p = new Pen(Color.Black, 1);
    graphics.DrawRectangle(p, Template.Image(source, refpic, 100));
}


来源:https://stackoverflow.com/questions/23454283/draw-rectangle-on-button-click-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!