The next way works, but it lags a bit, because Form1 acts like it loses its Focus.
Code:
public static class SuspendUpdate
{
private const int WM_SETREDRAW = 0x000B;
public static void Suspend(Control control)
{
Message msgSuspendUpdate = Message.Create(control.Handle, WM_SETREDRAW, IntPtr.Zero,
IntPtr.Zero);
NativeWindow window = NativeWindow.FromHandle(control.Handle);
window.DefWndProc(ref msgSuspendUpdate);
}
public static void Resume(Control control)
{
IntPtr wparam = new IntPtr(1);
Message msgResumeUpdate = Message.Create(control.Handle, WM_SETREDRAW, wparam,
IntPtr.Zero);
NativeWindow window = NativeWindow.FromHandle(control.Handle);
window.DefWndProc(ref msgResumeUpdate);
control.Invalidate();
}
}
Using:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Paint += Draw;
(new Thread(Method)).Start();
}
Bitmap bitmap = new Bitmap(200, 200);
private void Draw(object sender, PaintEventArgs e)
{
e.Graphics.DrawImage(bitmap, 0, 0);
}
private void Method()
{
using (Graphics g = Graphics.FromImage(bitmap))
g.Clear(Color.Red);
this.Invoke(new Action(delegate
{
SuspendUpdate.Suspend(this);
}));
bitmap = new Bitmap(100, 100);
using (Graphics g = Graphics.FromImage(bitmap))
g.Clear(Color.Yellow);
this.Invalidate();
this.Invoke(new Action(delegate
{
SuspendUpdate.Resume(this);
this.Invalidate();
this.Activate();
}));
}
}
public static class SuspendUpdate
{
private const int WM_SETREDRAW = 0x000B;
public static void Suspend(Control control)
{
Message msgSuspendUpdate = Message.Create(control.Handle, WM_SETREDRAW, IntPtr.Zero,
IntPtr.Zero);
NativeWindow window = NativeWindow.FromHandle(control.Handle);
window.DefWndProc(ref msgSuspendUpdate);
}
public static void Resume(Control control)
{
IntPtr wparam = new IntPtr(1);
Message msgResumeUpdate = Message.Create(control.Handle, WM_SETREDRAW, wparam,
IntPtr.Zero);
NativeWindow window = NativeWindow.FromHandle(control.Handle);
window.DefWndProc(ref msgResumeUpdate);
control.Invalidate();
}
}
}