刷新表格时如何减少闪烁?

时间:2018-07-03 04:46:43

标签: c# .net graphics bitmap

因此,无论何时我按住鼠标左键并在窗体上绘制矩形。 表单本身一直闪烁。 我尝试将DoubleBuffered属性设置为true,但这并没有改变任何内容。 有没有办法改变刷新率或类似的方法? 因为根据我的尝试,上面的示例和 SetStyle(ControlStyles.OptimizedDoubleBuffer, true);

它似乎没有任何改变

这是显示闪烁的gif

https://i.imgur.com/Wa3kmbM.gifv

private void Form1_Load(object sender, EventArgs e) 
{
    //Hide the Form
    this.Hide();
    label1.Visible = false;
    label2.Visible = false;

    //Create the Bitmap (This is an a black bitmap holding just the size.) (Bitmap is mutable)
    Bitmap printscreen = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
        Screen.PrimaryScreen.Bounds.Height);

    //Create a graphics object that's ready for alteration. `printscreen` is now a graphics Object
    Graphics graphics = Graphics.FromImage(printscreen);
    //Alter the graphics object which again is the printscreen
    graphics.CopyFromScreen(0, 0, 0, 0, printscreen.Size);


    //Create a temporary memory stream for the image
    using (MemoryStream s = new MemoryStream())
    {
        //save graphic variable into memory
        printscreen.Save(s, ImageFormat.Bmp);

        //Set the size of the picturebox
        pictureBox1.Size = new Size(Width, Height);

        //set the value of the picturebox.Image to an Image.FromStream and load the temp stream
        pictureBox1.Image = Image.FromStream(s);
    }
    //Show Form
    this.Show();

    //Cross Cursor
    Cursor = Cursors.Cross;
}

private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        //startX is holds the corresponding value of where the mouse is in relation to the pixels of the width
        //for instance, if it's all the way to the right, it holds the value of 1920.
        startX = e.X;
        startY = e.Y;
        selectPen = new Pen(Color.DimGray, 2);
        selectPen.DashStyle = DashStyle.Dash;

        pictureBox1.Refresh();
        start = true;
    }
}

private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{

    if (start)
    {
        pictureBox1.Refresh();
        //selectingWidth is equal to how much we have selected from the starting point.
        //Let's say the starting point is 10 and our current mouse position is at 10 then we have selected 0 pixels to the right.
        //However if we move our mouse 10 pixels to the right it means we have selected 10 pixels to the right.
        selectingWidth = e.X - startX;
        selectingHeight = e.Y - startY;

        //if the selectingWidth is less than 0, then set the origin to the current position of the mouse.
        var drawfromX = selectingWidth < 0 ? e.X : startX;
        var drawfromY = selectingHeight < 0 ? e.Y : startY;

        pictureBox1.Refresh();
        pictureBox1.CreateGraphics().DrawRectangle(selectPen,
            drawfromX,
            drawfromY,
            Math.Abs(selectingWidth),
            Math.Abs(selectingHeight));
    }
}

0 个答案:

没有答案