Is there anyway to make this piece of code more elegant? Cause, it´s It's not a nice view, but i can´tI can't really see a way to Improveimprove the looks of it, or shorten it.
But hopefully there is.
private void Send(CancellationToken CTSSend)
{
try
{
NativeMethods.Rect rc;
NativeMethods.GetWindowRect(hwnd, out rc);
IntPtr dc1;
IntPtr dc2 = NativeMethods.GetWindowDC(hwnd);
using (tcp = new TcpClient())
{
tcp.NoDelay = true;
while (!tcp.Connected && !CTSSend.IsCancellationRequested)
{
try
{
if (!tcp.Connected)
tcp.Connect(adress);
}
catch (Exception e)
{
if (e is SocketException) { Console.WriteLine(e.Message); }
else
MessageBox.Show(e.Message + " Tcp Connect : Send");
}
}
using (EncoderParameters JpegParam = new EncoderParameters())
using (JpegParam.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 50L))
using (Bitmap bmp = new Bitmap(rc.Width, rc.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb))
using (Graphics g = Graphics.FromImage(bmp))
using (var ms = new MemoryStream())
using (var tcpStream = tcp.GetStream())
while (tcp.Connected && !CTSSend.IsCancellationRequested)
{
try
{
dc1 = g.GetHdc();
NativeMethods.BitBlt(dc1, 0, 0, rc.Width, rc.Height, dc2, 0, 0, 13369376);
g.ReleaseHdc(dc1);
bmp.Save(ms, jpeg, JpegParam);
if (bsize != ms.Length)
{
bsize = ms.Length;
tcpStream.Write(BitConverter.GetBytes(bsize), 0, 4);
tcpStream.Write(ms.GetBuffer(), 0, (int)bsize);
}
ms.SetLength(0);
}
catch (Exception e)
{
if (e is IOException)
{
try { connect.Invoke(new Action(() => { connect.Text = "Connect"; })); }
catch (InvalidOperationException) { return; }
capcon = false;
}
else
MessageBox.Show(e.Message + ": Send Error");
}
}
}
}
catch (Exception e)
{
MessageBox.Show(e.Message + "SEND");
}
}
EDIT:
I am trying to find a nice way to put TCP reconnecting in another class, but i findI found a limitation where iI have to call return, onreturn
in the main class.
Here:
So, when it´s failingit fails, it goes out of the loop. I can also make it call ReturnReturn
, but it will do the same thing.
In the Class Caller iclass Caller
I have to use:
FastMethods.TCPReconnect(CTS, tcp, adress);
if (CTS.IsCancellationRequested)
return;
So asAs you can see, iI have to recheck for CTS. Is Is it possible to have it inside the other Classclass somehow?
Cause if iIf I use:
if (CTS.IsCancellationRequested)
return;