如何在程序中强制加载/重新加载winform

时间:2015-02-03 13:56:30

标签: c# winforms

我在互联网上搜索了一下,找到了涉及用Application.DoEvents()和重新加载winforms的解决方案 Control.Invalidate() Control.Update()

但它都不起作用。我正在尝试制作截取屏幕截图的程序,然后将像素随机向右移动。有点像屏幕熔化。

唯一的问题是表单只显示应用程序移动像素的时间。在他这样做的时候,我怎么能强迫他展示和重新画画。

这是绘画方法:

// Draw the screenshot...
private void Form1_Paint(object sender, EventArgs e)
{
    Bitmap myBitmap = new Bitmap(@".\screenshot.jpg");

    int Xcount;

    int maxXValue = 1919;
    int maxYValue = 1079;

    Random random = new Random();
    for (Xcount = 0; Xcount < maxXValue; Xcount++)
    {
        screenshot.Invalidate();
        screenshot.Image = myBitmap;
        screenshot.Update();

        for (int Ycount = 0; Ycount < maxYValue; Ycount++)
        {
            int calculatedX = Xcount + random.Next(0, maxXValue);
            if (calculatedX > maxXValue) calculatedX = maxXValue;

            myBitmap.SetPixel(Xcount, Ycount, myBitmap.GetPixel(calculatedX, Ycount));
        }
    }
}

2 个答案:

答案 0 :(得分:0)

我尝试了你的代码,它刷新就好了。我的猜测是你的Bitmap构造函数中的图像位置不正确?用直接路径测试它: new Bitmap(@"c:\yourImgDir\screenshot.jpg");并查看是否有效?

答案 1 :(得分:0)

我使用Form1_Load和Form1_Shown修复它,谢谢@Andy Korneyev 这是我现在的代码:

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

namespace ScreenOutput
{
    public partial class Form1 : Form
    {
    private Bitmap myBitmap = new Bitmap(@".\screenshot.jpg");
    private PictureBox screenshot;
    private int Xcount;
    private int maxXValue = 1919;
    private int maxYValue = 1079;
    public Form1()
    {
        InitializeComponent();

    }

    private void Form1_Load(object sender, EventArgs e)
    {
        screenshot.Load(@".\screenshot.jpg");
        screenshot.Image = myBitmap;
    }

    private void Form1_Paint(object sender, PaintEventArgs e)
    {

    }

    private void Form1_Shown(object sender, EventArgs e)
    {
        Random random = new Random();
        for (Xcount = 0; Xcount < maxXValue; Xcount++)
        {
            screenshot.Invalidate();
            screenshot.Update();

            for (int Ycount = 0; Ycount < maxYValue; Ycount++)
            {
                int calculatedX = Xcount + random.Next(0, maxXValue);
                if (calculatedX > maxXValue) calculatedX = maxXValue;
                myBitmap.SetPixel(Xcount, Ycount, myBitmap.GetPixel(calculatedX, Ycount));

            }
        }
    }
}
}