Monday, December 6, 2010

Throttle Socket In C#

public class ThrottleSocket
{
Socket _basesocket;
private long _maximumBytesPerSecond;
private long _byteCount;
private long _start;
public const long Infinite = 0;
public ThrottleSocket(Socket basesocket)
: this(basesocket, Infinite)
{
}
public ThrottleSocket(Socket basesocket, long maximumBytesPerSecond)
{
_basesocket = basesocket;
_start = CurrentMilliseconds;
_byteCount = 0;
_maximumBytesPerSecond = maximumBytesPerSecond;
}
protected long CurrentMilliseconds
{
get
{
return Environment.TickCount;
}
}
public long MaximumBytesPerSecond
{
get
{
return _maximumBytesPerSecond;
}
set
{
if (MaximumBytesPerSecond != value)
{
_maximumBytesPerSecond = value;
Reset();
}
}
}
protected void Throttle(int bufferSizeInBytes)
{
if (_maximumBytesPerSecond <= 0 || bufferSizeInBytes <= 0) { return; } _byteCount += bufferSizeInBytes; long elapsedMilliseconds = CurrentMilliseconds - _start; if (elapsedMilliseconds > 0)
{
long bps = _byteCount * 1000L / elapsedMilliseconds;
if (bps > _maximumBytesPerSecond)
{
long wakeElapsed = _byteCount * 1000L / _maximumBytesPerSecond;
int toSleep = (int)(wakeElapsed - elapsedMilliseconds);
if (toSleep > 1)
{
try
{
Thread.Sleep(toSleep);
}
catch (ThreadAbortException)
{
}
Reset();
}
}
}
}
public int Receive(byte[] buffer, int offset, int count,SocketFlags socketflag)
{
Throttle(count);
return _basesocket.Receive(buffer, offset, count,socketflag);
}
public int Receive(byte[] buffer)
{
Throttle(buffer.Length);
return _basesocket.Receive(buffer);
}
public void Send(byte[] buffer, int offset, int count,SocketFlags socketflag)
{
Throttle(count);
_basesocket.Send(buffer, offset, count,socketflag);
}
public void Send(byte[] buffer)
{
Throttle(buffer.Length);
_basesocket.Send(buffer);
}
protected void Reset()
{
long difference = CurrentMilliseconds - _start;
if (difference > 1000)
{
_byteCount = 0;
_start = CurrentMilliseconds;
}
}
}

Sunday, December 5, 2010

Capture Screen in C#


Bitmap bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb);
Graphics gfxScreenshot = Graphics.FromImage(bmpScreenshot);
gfxScreenshot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy);
bmpScreenshot.Save("filename.png", ImageFormat.Png);

Click Through Forms in C#

To make a Click Through Form
use the code below

{
......
this.TransparencyKey = this.BackColor;
....
}

To make a Panel transparent use the code below
{
......
this.TransparencyKey = this.panel1.BackColor;
......
}