Hey guys, I have written a "bot" program that is scriptable to do certain automated tasks, e.g. type, move mouse, interact with windows etc.
I have a little window on this bot program (picture box) which captures the screen and places a crosshair on the window which shows the user where the mouse is on the screen:
public void CaptureThread()
{
try
{
Bitmap scrnimg = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format24bppRgb);
while (this.Visible)
{
while (this.WindowState == FormWindowState.Minimized)
Thread.Sleep(750);
try
{
Display.CaptureScreenRegion(Screen.PrimaryScreen.Bounds, scrnimg);
Pen Pen;
switch (CrosshairColour)
{
default:
case "Red":
Pen = new Pen(Color.Red, 5);
break;
case "Blue":
Pen = new Pen(Color.Blue, 5);
break;
case "Green":
Pen = new Pen(Color.Green, 5);
break;
case "Lime":
Pen = new Pen(Color.LimeGreen, 5);
break;
case "Magenta":
Pen = new Pen(Color.Magenta, 5);
break;
case "Black":
Pen = new Pen(Color.Black, 5);
break;
case "White":
Pen = new Pen(Color.White, 5);
break;
}
Graphics g = Graphics.FromImage(scrnimg);
g.CompositingMode = CompositingMode.SourceCopy;
float formLeft = Screen.PrimaryScreen.Bounds.Left;
float formTop = Screen.PrimaryScreen.Bounds.Top;
float formRight = Screen.PrimaryScreen.Bounds.Right;
float formBottom = Screen.PrimaryScreen.Bounds.Bottom;
// Place a black box over the location of the main window
Rectangle r = new Rectangle(this.Location.X + splitContainer1.Location.X, this.Location.Y + splitContainer1.Location.Y, pictureBox1.Width + 24, pictureBox1.Height + 71);
Pen Box = new System.Drawing.Pen(Color.Black, 1);
g.FillRectangle(Box.Brush, r);
g.DrawRectangle(Pen, r);
if (DrawCrosshair)
{
g.DrawLine(Pen, 0, Cursor.Position.Y, Cursor.Position.X, Cursor.Position.Y);
g.DrawLine(Pen, Cursor.Position.X, 0, Cursor.Position.X, Cursor.Position.Y);
g.DrawLine(Pen, formRight, Cursor.Position.Y, Cursor.Position.X, Cursor.Position.Y);
g.DrawLine(Pen, Cursor.Position.X, formBottom, Cursor.Position.X, Cursor.Position.Y);
}
g.Dispose();
SetMirror(scrnimg);
//pictureBox1.Image = scrnimg;
// Set the title of the main window
WindowTitle("(" + Cursor.Position.X + ", " + Cursor.Position.Y + ")");
}
catch { }
// Range from 10 - 1000ms
Thread.Sleep(MirrorFreq);
}
}
catch { }
}
delegate void SetMirrorCallback(Bitmap bmp);
private void SetMirror(Bitmap bmp)
{
if (pictureBox1.InvokeRequired)
{
SetMirrorCallback d = new SetMirrorCallback(SetMirror);
this.Invoke(d, new object[] { bmp });
}
else
{
pictureBox1.Image = bmp;
}
}
As you can probably guess, this uses up anywhere from 8% to 17% of my processor time while the window is up, and this also is causing a memory leak.
Does anybody have a more efficient way of doing this that will not cause memory leaks and also lower the cpu usage?
Thanks.