Posts mit Tag: Control

c# – WorkingSetControl / RamControl: Displaying the Working Set size / current RAM usage of an application

English
Did you ever want to display the Working Set size / current RAM usage of your c# application? If the answer to this question is ‘yes’, here is your solution. If the answer is ‘no’ you still might find some usable code snippets in the control.

Deutsch
Es ist relativ einfach die aktuelle Speicherbelegung in einem c# Programm herauszufinden. Ich habe dies Funktionalität in ein kleinen Control verpackt.

Screenshot des Controls:
WorkingSetControl

View Code CSHARP
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Threading;
using System.Diagnostics;
using System.Drawing;
 
namespace MyProject
{
    /// <summary>
    /// Control to display the  current WorkingSet size. Aka "RamControl". Just call Start to start the monitoring.
    /// </summary>
    class WorkingSetControl : Control
    {
        Thread t1;
        bool active = false;
 
        public WorkingSetControl()
        {
            SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
        }
 
        /// <summary>
        /// Start displaying the current WorkingSet size. If you don't call Start you won't see a thing!
        /// </summary>
        internal void Start()
        {
            // start only if not started yet
            if (t1 == null)
            {
                // although we could use a lambda expression to create this thread don't use one to be .NET 2.0 compatible.
                t1 = new Thread(run);
 
                // if you *HAVE* to use a lambda expression, fine have fun with your cryptic code:
                /*
                t1 = new Thread(() =>
                {
                    while (active)
                    {
                        Invalidate();
                        Thread.Sleep(100);
                    }
                });
                */
 
                // set active to true, so our run method does actually run in loops 'n loops 'n loops until active is set to false ==> see Dispose.
                active = true;
                t1.Start();
            }
        }
 
        void run()
        {
            while (active)
            {
                Invalidate();
                Thread.Sleep(100);
            }
        }
 
        /// <summary>
        /// Get and draw the WorkingSet size
        /// </summary>
        /// <param name="e"></param>
        protected override void OnPaint(PaintEventArgs e)
        {
            string ram = "xxx";
 
            // Only get the WorkingSet size if the control is in active mode.
            // This prevents the control displaying the WorkingSet size of Visual Studio in the designer (which works actually, but is somehow confusing).
            if (active)
            {
                long lngSessMemory = Process.GetCurrentProcess().WorkingSet64;
                ram = (Convert.ToDouble(lngSessMemory) / 1000 / 1000).ToString("0.00");
            }
 
            // do the grphics stuff
            e.Graphics.Clear(BackColor);
            e.Graphics.DrawString("WorkingSet: " + ram + " MB", Font, new SolidBrush(ForeColor), 0, 0);
        }
 
        /// <summary>
        /// Lets make sure our thread terminates at some point in time.
        /// </summary>
        /// <param name="disposing"></param>
        protected override void Dispose(bool disposing)
        {
            // I know we should wait for the thread to actually funish by using t1.Join() but that would slow down this methob by up to 100ms.
            // If you have any Problems with controls not disposing properly, let me know and send me a solution ;)
            active = false;
            base.Dispose(disposing);
        }
    }
}

c# – eigenes Control, Keys.Up, Down, Left, Right: OnKeyDown / OnKeyPress vs. ProcessCmdKey

Wer ein eigenes Control (Steuerelement) in c# erstellt und dachte, dass er mit OnKeyDown Pfeiltasten erkennen kann ist auf dem Holzweg:

View Code CSHARP
1
2
3
4
5
6
protected override void OnKeyDown(KeyEventArgs e)
{
	/* wird für Pfeiltasten nicht aufgerufen */
	base.OnKeyDown(e);
	if (e.KeyCode == Keys.Up) MoveIndex(-1);
}

Bei Druck auf die Pfeiltasten (Keys.Up, Keys.Down, Keys.Left, Keys.Right) wird weder OnKeyDown noch OnKeyPress aufgerufen.

Die Lösung bringt ProcessCmdKey:

View Code CSHARP
1
2
3
4
5
6
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
	if (keyData == Keys.Up) MoveIndex(-1);
 
	return base.ProcessCmdKey(ref msg, keyData);
}

Hier muss allerdings beachtet werden, dass in keyData auch Strg, Shift und Alt kodiert werden. keyData == Keys.Up ist nur true, wenn keine Steuerungstaste (Strg, Shift, Alt) gleichzeitig gedrückt wurde.

Welche Tasten gedrückt sind lässt sich folgendermaßen herausfinden:

View Code CSHARP
1
2
3
4
bool shift = (keyData & Keys.Shift) != 0;
bool control = (keyData & Keys.Control) != 0;
bool alt = (keyData & Keys.Alt) != 0;
Keys unmodifiedKey = (keyData & Keys.KeyCode);

TextControl

In c#.Net gibt es einen Label. Dieser ist recht praktisch, solange man nicht weitere Steuerelemente direkt anschließend platzieren möchte.

Die einzige Möglichkeit einen Label zu realisieren, der überhaupt kein Padding hat, ist diesen selbst zu schreiben.

View Code CSHARP
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
class TextControl : Control
{
	private Brush brush = new SolidBrush(Color.Black);
	private StringFormat stringFormat;
	private Graphics graphics = null;
 
	internal static StringFormat GetStringFormat()
	{
		StringFormat stringFormat = new StringFormat();
		stringFormat.Alignment = StringAlignment.Center;
		stringFormat.LineAlignment = StringAlignment.Near;
		stringFormat.Trimming = StringTrimming.None;
		stringFormat.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.MeasureTrailingSpaces;
		return stringFormat;
	}
 
	public TextControl()
	{
		this.stringFormat = GetStringFormat();
		graphics = this.CreateGraphics();
		this.TabStop = false;
	}
	~TextControl()
	{
		graphics.Dispose();
	}
 
	protected override void OnPaint(PaintEventArgs e)
	{
		base.OnPaint(e);
		RePaint();
	}
	void RePaint()
	{
		Graphics g = this.CreateGraphics();
		g.Clear(this.BackColor);
		g.DrawString(base.Text, base.Font, brush, base.ClientRectangle, stringFormat);
	}
	protected override void OnParentChanged(EventArgs e)
	{
		base.OnParentChanged(e);
		if (this.AutoSize)
		{
			DoAutoSize();
		}
	}
 
	[System.ComponentModel.Browsable(true)]
	[System.ComponentModel.Category("Layout")]
	public override bool AutoSize
	{
		get { return base.AutoSize; }
		set { base.AutoSize = value; }
	}
 
	protected override void OnForeColorChanged(EventArgs e)
	{
		base.OnForeColorChanged(e);
		brush.Dispose();
		brush = new SolidBrush(this.ForeColor);
	}
 
	protected override void OnTextChanged(EventArgs e)
	{
 
		base.OnTextChanged(e);
		if (this.AutoSize &amp;&amp; this.Parent != null)
		{
			DoAutoSize();
		}
	}
	void DoAutoSize()
	{
		RectangleF rf = MeasureText(base.Text, graphics, stringFormat, base.Font);
		this.Size = new Size((int)rf.Width, (int)rf.Height);
	}
 
	public static RectangleF MeasureText(string text, Graphics g, StringFormat sf, Font font)
	{
		if (text.Length &gt; 0)
		{
			sf.SetMeasurableCharacterRanges(new CharacterRange[] { new CharacterRange(0, text.Length) });
			Region[] stringRegions = g.MeasureCharacterRanges(text, font, new RectangleF(0, 0, 1000, 100), sf);
			return stringRegions[0].GetBounds(g);
		}
		else
		{
			return new RectangleF(new PointF(0, 0), new SizeF(0, 0));
		}
	}
	public static float getTextLength(string Text, Graphics g, StringFormat sf, Font font)
	{
		RectangleF rf = MeasureText(Text, g, sf, font);
		return rf.Width;
	}
 
	public static int GetMaxTextByLength(string text, int maxLength, Graphics g, StringFormat sf, Font font)
	{
		if (getTextLength(text, g, sf, font) &lt;= maxLength)
		{
			return text.Length;
		}
		string[] parts = text.Split(new char[] { ' ' }, StringSplitOptions.None);
		int len = 0;
		string current = parts[0];
		len = (int)getTextLength(current, g, sf, font);
		if (len &gt; maxLength) return 0;
		int n = 1;
		while (len &lt; maxLength)
		{
			current += " " + parts[n];
			n++;
			len = (int)getTextLength(current, g, sf, font);
		}
		return len;
 
	}
 
	protected override void OnAutoSizeChanged(EventArgs e)
	{
		base.OnAutoSizeChanged(e);
		this.OnTextChanged(e);
	}
 
}

WordPress Themes