-
Notifications
You must be signed in to change notification settings - Fork 5
/
WindowsFormsExtensions.cs
64 lines (53 loc) · 1.83 KB
/
WindowsFormsExtensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
using System.Drawing;
using System.Runtime.InteropServices;
namespace System.Windows.Forms
{
public static class ControlExtensions
{
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr SendMessage(IntPtr hWnd, int Msg, int wParam, IntPtr lParam);
/// <summary>
/// Prevents a control from redrawing. This is useful when performing bulk updates.
/// </summary>
public static void SetRedraw(this Control control, bool allow)
{
const int WM_SETREDRAW = 0xB;
SendMessage(control.Handle, WM_SETREDRAW, allow ? 1 : 0, IntPtr.Zero);
}
/// <summary>
/// Allows any amount of updating/formatting while handling the details of preserving
/// the current position and selection in the box (while also preventing flicker).
/// </summary>
public static void MinimalImpactFormat(this RichTextBox box, Action<RichTextBox> f)
{
// Grab previous state
var (prevStart, prevLen) = (box.SelectionStart, box.SelectionLength);
var leftId = box.GetCharIndexFromPosition(new Point(3, 3));
var rightId = box.GetCharIndexFromPosition(new Point(box.Width - 3, box.Height - 3));
// Prevent flicker
box.SetRedraw(false);
f(box);
// Reset our view
box.SelectionLength = 0;
box.SelectionStart = 0;
// Restore the previous view
box.SelectionStart = leftId;
box.SelectionLength = Math.Max(0, rightId - leftId);
// Restore the previous selection
box.SelectionLength = prevLen;
box.SelectionStart = prevStart;
// Resume drawing and force a redraw
box.SetRedraw(true);
box.Invalidate();
}
}
public static class SystemExtensions
{
public static string ReplaceFirst(this string text, string search, string replace)
{
int pos = text.IndexOf(search);
if (pos < 0) return text;
return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
}
}
}