我有一个 Panel 来填充父表单。
我使用了一个定时器来捕捉屏幕,
并定期将截图设置为Panel的背景图。
然而,它遇到了疯狂的闪烁。我能做些什么来解决它?
//Part of code
public partial class Form1 : Form
{
DxScreenCapture sc = new DxScreenCapture();
public Form1()
{
InitializeComponent();
panelMain.BackgroundImageLayout = ImageLayout.Zoom;
}
private void Form1_Load(object sender, EventArgs e)
{
}
void RefreshScreen()
{
Surface s = sc.CaptureScreen();
DataStream ds = Surface.ToStream(s, ImageFileFormat.Bmp);
panelMain.BackgroundImage = Image.FromStream(ds);
s.Dispose();
}
private void timer1_Tick(object sender, EventArgs e)
{
RefreshScreen();
}
}
最佳答案
尝试使用双缓冲面板。继承面板,将 DoubleBuffered 设置为 true 并使用该面板而不是默认面板:
namespace XXX
{
/// <summary>
/// A panel which redraws its surface using a secondary buffer to reduce or prevent flicker.
/// </summary>
public class PanelDoubleBuffered : System.Windows.Forms.Panel
{
public PanelDoubleBuffered()
: base()
{
this.DoubleBuffered = true;
}
}
}
编辑
此外,我想鼓励您多注意一下您使用的资源。每当一个对象实现了 IDisposable 接口(interface)时——当不再需要时释放该对象。这在处理流等非托管资源时非常重要!
void RefreshScreen()
{
using (Surface s = sc.CaptureScreen())
{
using (DataStream ds = Surface.ToStream(s, ImageFileFormat.Bmp))
{
Image oldBgImage = panelMain.BackgroundImage;
panelMain.BackgroundImage = Image.FromStream(ds);
if (oldBgImage != null)
oldBgImage.Dispose();
}
}
}
关于c# - 面板背景图像闪烁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21873441/