I have just written the C# Code that is recording the screenshot of the desktop.It works on Winforms but not works in windows service.
My code as below:
public partial class ScreenCapture : ServiceBase
{
bool rec = false;
Rectangle screenSize = Screen.PrimaryScreen.Bounds;
UInt32 frameCount = 0;
VideoFileWriter writer;
int width = SystemInformation.VirtualScreen.Width;
int height = SystemInformation.VirtualScreen.Height;
AForge.Video.ScreenCaptureStream streamVideo;
Stopwatch stopWatch = new Stopwatch();
public ScreenCapture()
{
InitializeComponent();
writer = new VideoFileWriter();
if (!System.Diagnostics.EventLog.SourceExists("MySource"))
{
System.Diagnostics.EventLog.CreateEventSource("MySource", "MyLog");
}
eventLog1.Source = "MySource";
this.CanHandleSessionChangeEvent = true;
}
protected override void OnSessionChange(SessionChangeDescription changeDescription)
{
string folderName = #"C:\LoginLog";
if (changeDescription.Reason == SessionChangeReason.SessionLogon)
{
eventLog1.WriteEntry(changeDescription.SessionId + " User Logon");
if (!Directory.Exists(folderName))
{
Directory.CreateDirectory(folderName);
}
StartRec(folderName);
}
else if (changeDescription.Reason == SessionChangeReason.SessionLogoff)
{
eventLog1.WriteEntry(changeDescription.SessionId + " User Logoff");
rec = false;
}
else if (changeDescription.Reason == SessionChangeReason.SessionLock)
{
eventLog1.WriteEntry(changeDescription.SessionId + " User Lock");
rec = false;
}
else if (changeDescription.Reason == SessionChangeReason.SessionUnlock)
{
eventLog1.WriteEntry(changeDescription.SessionId + " User Unlock");
if (!Directory.Exists(folderName))
{
Directory.CreateDirectory(folderName);
}
StartRec(folderName);
}
base.OnSessionChange(changeDescription);
}
private void StartRec(string path)
{
if (rec == false)
{
rec = true;
frameCount = 0;
string time = DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ssff");
string compName = Environment.UserName;
string fullName = path + "\\" + compName.ToUpper() + "_" + time;
try
{
writer.Open(
fullName + ".mp4",
width,
height,
10,
VideoCodec.MPEG4, 1000000);
}
catch (Exception ex)
{
eventLog1.WriteEntry("Exception StartRec: " + ex.Message);
}
DoJob();
}
}
private void DoJob()
{
try
{
Rectangle screenArea = Rectangle.Empty;
foreach (System.Windows.Forms.Screen screen in
System.Windows.Forms.Screen.AllScreens)
{
screenArea = Rectangle.Union(screenArea, screen.Bounds);
}
streamVideo = new ScreenCaptureStream(screenArea);
streamVideo.NewFrame += new NewFrameEventHandler(video_NewFrame);
streamVideo.Start();
stopWatch.Start();
}
catch (Exception ex)
{
eventLog1.WriteEntry("Exception DoJob: " + ex.Message);
}
}
private void video_NewFrame(object sender, AForge.Video.NewFrameEventArgs eventArgs)
{
try
{
if (rec)
{
frameCount++;
writer.WriteVideoFrame(eventArgs.Frame);
}
else
{
stopWatch.Reset();
Thread.Sleep(500);
streamVideo.SignalToStop();
Thread.Sleep(500);
writer.Close();
}
}
catch (Exception ex)
{
eventLog1.WriteEntry("Exception Video New Frame: " + ex.Message);
}
}
}
And the service can save a .mp4 file, but it cannot open it.I think windows service can not capture desktop screen.
Can anybody help me how to solve this problem?
thanks in advance.
You need to set windows service run under interactive account,
To do so you need to go to properties of service got to logon tab and login by
your windows account.
Related
I'm building a Taxi app and wanted to calculate the distance while the trip is going and update from the driver app side
I used Geolocator for live updates from https://github.com/jamesmontemagno/GeolocatorPlugin, I'm getting random locations and it's not stable on live updates so i changed getting the location after a minute
private async Task StartTrackingAsync(bool tracking)
{
try
{
PermissionStatus hasPermission = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Location);
if (hasPermission != PermissionStatus.Denied)
{
// Permission Granted
// check for req
if (tracking)
{
// Check is listening...
if (CrossGeolocator.Current.IsListening)
{
// Start
CrossGeolocator.Current.PositionChanged += CrossGeolocator_Current_PositionChanged;
CrossGeolocator.Current.PositionError += CrossGeolocator_Current_PositionError;
}
else
{
CrossGeolocator.Current.PositionChanged += CrossGeolocator_Current_PositionChanged;
CrossGeolocator.Current.PositionError += CrossGeolocator_Current_PositionError;
object aType = "Automotive Navigation";
if (await CrossGeolocator.Current.StartListeningAsync(TimeSpan.FromSeconds(5), 50,
true, new ListenerSettings
{
ActivityType = ActivityType.AutomotiveNavigation,
AllowBackgroundUpdates = true,
DeferLocationUpdates = true,
DeferralDistanceMeters = 100,
DeferralTime = TimeSpan.FromSeconds(50),
ListenForSignificantChanges = true,
PauseLocationUpdatesAutomatically = false
}))
{
tracking = true;
}
}
}
else
{
CrossGeolocator.Current.PositionChanged -= CrossGeolocator_Current_PositionChanged;
CrossGeolocator.Current.PositionError -= CrossGeolocator_Current_PositionError;
await CrossGeolocator.Current.StopListeningAsync();
tracking = false;
}
}
else
{
// Permission Denied
await DisplayAlert("Location Error", "Error Getting Location", "OK");
}
}
catch (Exception ex)
{
// Error Accured
await DisplayAlert("Location Error", "Error Getting Location: " + ex.Message, "OK");
}
}
private void CrossGeolocator_Current_PositionError(object sender, PositionErrorEventArgs e)
{
}
private void CrossGeolocator_Current_PositionChanged(object sender, PositionEventArgs e)
{
Device.BeginInvokeOnMainThread(async () =>
{
Plugin.Geolocator.Abstractions.Position position = e.Position;
if (Cposition != e.Position)
{
Cposition = e.Position;
mainmap.MoveToRegion(MapSpan.FromCenterAndRadius(new Xamarin.Forms.Maps.Position(position.Latitude, position.Longitude), Distance.FromMiles(1)).WithZoom(2));
loader.IsVisible = false;
mainmap.IsVisible = true;
local.Lat = position.Latitude;
local.Lng = position.Longitude;
}
});
}
private void DistanceUpdate(bool w = false)
{
Device.StartTimer(new TimeSpan(0, 0, 1), () =>
{
UpdateDistance();
return w;
});
}
private async void UpdateDistance()
{
// Get Trip Location
Models.Location SLocal = Trip.Location;
Xamarin.Essentials.Location startTrip = new Xamarin.Essentials.Location(SLocal.Lat, SLocal.Lng);
try
{
if (local != null)
{
Xamarin.Essentials.Location OnTrip = new Xamarin.Essentials.Location(local.Lat, local.Lng);
double distance = Xamarin.Essentials.Location.CalculateDistance(startTrip, OnTrip, DistanceUnits.Kilometers);
double t = tdistance + distance;
tdistance = Math.Round(t, 2);
if (Trip.Key != null)
{
_firebaseDatabase.UpdateTripDriverLocation(Trip.Key, local);
if (Trip.Status == "Started")
{
_firebaseDatabase.UpdateTripLocation(Trip.Key, local);
}
}
}
}
catch (Exception ex)
{
// Unable to get location
await DisplayAlert(ex.Source, "ERROR: " + ex.Message, "OK");
}
}
I'm not getting the current location but a random location and the distance produces more 5000km in 2 minutes before the driver starts moving
Using visual studios Windows forms on c#, I'm making a chatprogram with unlimited clients and one server. The server has to be activated before I connect any client. However, after connecting one or more clients and closing one of them, the server crashes. I can nor close it or send any data from my clients to it without getting an error. The CPU usage of my computer rises to 50% during the crash. After I manage to close the server through task manager, different code lines are highlighted, indicating the error.
Here's my server code:
namespace TCPa
{ // skapar en lista med tcp clients
// säg till så att send funktioner tar tcp clients som input i
metoderna och referera till metoderna
// och loopa genom listan, som kallar metoden i lista.
public partial class Server : Form
{
TcpClient klient = null;
List<TcpClient> klientLista = new List<TcpClient>();
TcpListener lyssnare;
int port = 0;
public Server()
{
InitializeComponent();
}
private void btnTaEmot_Click(object sender, EventArgs e)
{
try
{
port = int.Parse(tbxPort.Text);
if (port >= 1024 && port <= 65535)
{
les(port);
}
else
{
MessageBox.Show("Skriv in ett giltigt portnummer mellan 1024 och 65535");
}
}
catch (Exception)
{
MessageBox.Show("Skriv in ett giltigt portnummer mellan 1024 och 65535");
}
}
public void les(int portT)
{
btnTaEmot.Enabled = false;
tbxPort.Enabled = false;
try
{
lyssnare = new TcpListener(IPAddress.Any, portT);
lyssnare.Start();
}
catch (Exception error)
{
MessageBox.Show(error.Message, Text);
return;
}
StartAccepting();
}
public async void StartAccepting()
{
try
{
klient = await lyssnare.AcceptTcpClientAsync();
klientLista.Add(klient);
}
catch (Exception error)
{
MessageBox.Show(error.Message, Text);
return;
}
StartReading(klient);
StartAccepting();
}
public async void StartReading(TcpClient k)
{
byte[] buffer = new byte[1024];
int n = 0;
try
{
///NEW
n = await k.GetStream().ReadAsync(buffer, 0, 1024);
if (n <= 0)
{
klient.Close();
}
////NEW
}
catch (Exception error)
{
MessageBox.Show(error.Message, Text);
return;
}
StartSending(k, Encoding.Unicode.GetString(buffer, 0, n));
tbxLogg.AppendText(Encoding.Unicode.GetString(buffer, 0, n));
StartReading(k);
}
public async void StartSending(TcpClient klientSomSkickar, string message)
{
if (klientLista.Count > 0)
{
byte[] utData = Encoding.Unicode.GetBytes(message);
foreach (TcpClient klient in klientLista)
{
try
{
if (klient != klientSomSkickar)
{
await klient.GetStream().WriteAsync(utData, 0, utData.Length);
}
}
catch (Exception error)
{
MessageBox.Show(error.Message, Text); return;
}
}
}
}
private void Server_FormClosing(object sender, FormClosingEventArgs e)
{
lyssnare.Stop();
if (klient != null && klient.Connected)
{
klient.Close();
}
}
}
}
Here's my client code
namespace Klient
{
public partial class Klient : Form
{
TcpClient klient = new TcpClient();
public Klient()
{
InitializeComponent();
btnSend.Enabled = false;
}
private void btnAnslut_Click(object sender, EventArgs e)
{
Connect();
}
private async void Connect()
{
IPAddress adress = IPAddress.Parse(tbxIP.Text);
int port = int.Parse(tbxPort.Text);
try
{
await klient.ConnectAsync(adress, port);
}
catch (Exception error)
{
MessageBox.Show(error.Message, Text);
return;
}
if (klient.Connected)
{
btnAnslut.Enabled = false;
btnSend.Enabled = true;
tbxNmn.Enabled = false;
tbxMedd.Focus();
}
StartReading(klient);
}
private async void btnSend_Click(object sender, EventArgs e)
{
if (klient.Connected)
{
string namn = tbxNmn.Text;
string tid = DateTime.Now.ToString("HH:mm tt");
if (String.IsNullOrEmpty(tbxMedd.Text) || String.IsNullOrWhiteSpace(tbxMedd.Text))
{
MessageBox.Show("Skriv in ditt meddelande");
}
else
{
byte[] utData = Encoding.Unicode.GetBytes("<" + " " + namn + " " + ">" + " " + tid + ":" + "\t" + tbxMedd.Text + "\r\n");
try
{
tbxLogg.AppendText("<" + " " + namn + " " + ">" + " " + tid + ":" + "\t" + tbxMedd.Text + "\r\n");
await klient.GetStream().WriteAsync(utData, 0, utData.Length);
}
catch (Exception error)
{
MessageBox.Show(error.Message, Text);
return;
}
}
}
tbxMedd.Clear();
}
public async void StartReading(TcpClient k)
{
byte[] buffer = new byte[1024];
int n = 0;
try
{
n = await k.GetStream().ReadAsync(buffer, 0, 1024);
}
catch (Exception error)
{
MessageBox.Show(error.Message, Text);
return;
}
tbxLogg.AppendText(Encoding.Unicode.GetString(buffer, 0, n));
StartReading(k);
}
private void Klient_FormClosing(object sender, FormClosingEventArgs e)
{
if (klient != null)
klient.Close();
}
}
}
Any help is appreciated!!
I am working on this GUI for serial port application. I recently added stop and wait protocols to the application. Surprisingly my disconnect button stopped working. I have thought through the logic and I have not been able to find the problem.
namespace WindowsFormsApplication5
{
public partial class Form1 : Form
{
public bool packetreceived = false;
private SerialPort sp = null; //<---- serial port at form level
public delegate void AddDataDelegate(String myString);
public AddDataDelegate myDelegate;
//delegate variable to disconnect
public AddDataDelegate disconnectDelegate = null;
public void AddDataMethod(String myString)
{
richTextBox1.AppendText(myString);
}
/**
* Takes byte array and returns a string representation
*
*/
public String parseUARTData(byte[] data)
{
if (data.Length == 11)
{
String rv = "";
DataFields d = new DataFields();
if (!packetreceived)
{
d = mainLogic.parseData(data);
packetreceived = true;
}
//TODO
System.Threading.Thread.Sleep(5000);
if (d.sequence == 0)
{
sp.Write("1\r\n");
}
else
{
sp.Write("0\r\n");
}
packetreceived = false;
//now display it as a string
rv += STR_OPCODE + " = " + d.opcode + "\n";
rv += STR_CRC + " = " + d.crc + "\n";
rv += STR_SEQ + " = " + d.sequence + "\n";
rv += STR_FLAGS + " = " + d.flags + "\n";
rv += STR_TEMP + " = " + d.temperature + "\n";
rv += STR_HUMID + " = " + d.humidity + "\n";
rv += STR_PH + " = " + d.ph + "\n";
return rv + "\n\n";
}
else
{
return Encoding.ASCII.GetString(data);
}
}
private void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string s = sp.ReadExisting();
if (disconnectDelegate != null)
{
disconnectDelegate.Invoke(s);
}
richTextBox1.Invoke(this.myDelegate, new Object[] { parseUARTData(Encoding.ASCII.GetBytes(s)) });
}
private void button1_Click(object sender, EventArgs e)
{
connect.Enabled = false;
try
{
// open port if not already open
// Note: exception occurs if Open when already open.
if (!sp.IsOpen)
{
//sp.PortName = this.comboBox1.SelectedItem.ToString();
sp.Open();
}
// send data to port
sp.Write("####,###########\r\n");
disconnect.Enabled = true;
}
catch (Exception)
{
// report exception to user
Console.WriteLine(e.ToString());
}
}
private void button2_Click(object sender, EventArgs e)
{
connect.Enabled = true;
try
{
// open port if not already open
// Note: exception occurs if Open when already open.
if (sp.IsOpen)
{
// send data to port
sp.Write("+++\r\n");
//add the delegate
disconnectDelegate = new AddDataDelegate(onDisconnect);
//sp.WriteTimeout = 500;
// sp.Write("####,0\r\n");
}
}
catch (Exception)
{
Console.WriteLine(e.ToString());
}
finally
{
disconnect.Enabled = false;
}
}
public void OnApplicationExit(object sender, EventArgs e)
{
sp.Close();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
//foreach (string port in ports)
//{
// comboBoxSerialPorts.Items.Add(port);
//}
}
private void onDisconnect(string msg)
{
string trimmedMsg = msg.Trim();
if (trimmedMsg.Equals("OK"))
{
//send the second time
sp.Write("##,0\r\n");
//null the object
disconnectDelegate = null;
}
}
private void comPort_Click(object sender, EventArgs e)
{
try
{
if (sp.IsOpen)
{
//send data to port
sp.Write("1\r\n");
MessageBox.Show("bluetooth is transmitting data...");
//message box telling user that you are asking for data.
}
}
catch (Exception)
{
// report exception to user
Console.WriteLine(e.ToString());
}
}
Basically I need to communicate with a COM serial printer. There are 2 timers, one will print one ticket at time, and the others will hang up checking for errors and resuming the printing when the errors are gone.
For example: Printer is printing but if I press the pause button an error (read in the buffer) will get some booleans to 1 and after I read them I am able to tell what the error is and stop the printing.
My problem is in the method ErrorTimer_Elapsed() which is the timer elapsed event and probably is linked to the ErrorCheck and SendToCom (which is the printing method). The problem is that program detects errors well, but when in ErrorTimer_Elapsed() I try to repeatdly check for error status changes, I get IO errors like:
-Can't acces COM PORT
-The resource you required is in use
and so on.
Can you help me? Thanks, here's the code (about 180 lines), I'm bumping my head on this since 3 days :( :
using System;
using System.Collections;
using System.Configuration;
using System.IO;
using System.IO.Ports;
using System.Windows.Forms;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
#region Variabili di istanza
private ArrayList _filesToPrint = new ArrayList();
private static SerialPort _serialPort1 = new SerialPort();
private string _portName = ConfigurationSettings.AppSettings["COM"];
private string FilesPath = ConfigurationSettings.AppSettings["Path"];
private System.Timers.Timer PrintTimer = new System.Timers.Timer(2000);
private System.Timers.Timer ErrorTimer = new System.Timers.Timer(3500);
private bool PrintTimerIsActive = true;
private string HsCOMerrorStrings, PrintErrors;
#endregion
public Form1()
{
_serialPort1.PortName = _portName;
_serialPort1.ReadTimeout = 1000;
_IfFileExistsPrint();
}
private void _IfFileExistsPrint()
{
foreach (string file in Directory.GetFiles(FilesPath))
_filesToPrint.Add(file);
FileSystemWatcher SysWatch = new FileSystemWatcher(FilesPath, "*.*");
SysWatch.Created += new FileSystemEventHandler(SysWatch_Created);
SysWatch.EnableRaisingEvents = true;
PrintTimer.Elapsed += new System.Timers.ElapsedEventHandler(Timer_Elapsed);
PrintTimer.Start();
ErrorTimer.Elapsed += new System.Timers.ElapsedEventHandler(ErrorTimer_Elapsed);
}
private void SysWatch_Created(object Sender, FileSystemEventArgs w)
{
_filesToPrint.Add(w.FullPath);
}
private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (_filesToPrint.Count > 0 && PrintTimerIsActive)
{
PrintTimer.Stop();
SendFilesToCom(_filesToPrint[0].ToString());
MessageBox.Show("Printing file :" + _filesToPrint[0].ToString());
File.Delete(_filesToPrint[0].ToString());
_filesToPrint.RemoveAt(0);
_filesToPrint.TrimToSize();
Console.Write(HsCOMerrorStrings);
PrintTimer.Start();
PrintErrors = ErrorCheck(HsCOMerrorStrings);
}
}
private void ErrorTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs d)
{
if (!_serialPort1.IsOpen)
{
try
{
_serialPort1.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex.Data);
}
}
try
{
HsCOMerrorStrings = _serialPort1.ReadExisting();
_serialPort1.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Data);
}
Console.WriteLine(ErrorCheck(HsCOMerrorStrings));
}
private string ErrorCheck(string COMHostStatusReturn)
{
string ErrorsReturn = System.String.Empty;
string[] COMCode = COMHostStatusReturn.Split(',');
if (COMCode[1] == "1") { ErrorsReturn += "Carta Esaurita" + Environment.NewLine; }
if (COMCode[2] == "1") { ErrorsReturn += "Stampante in Pausa" + Environment.NewLine; }
if (COMCode[5] == "1") { ErrorsReturn += "Memoria Stampante Esaurita" + Environment.NewLine; }
if (COMCode[9] == "1") { ErrorsReturn += "Memoria RAM corrotta" + Environment.NewLine; }
if (COMCode[10] == "1") { ErrorsReturn += "Temperatura troppo bassa" + Environment.NewLine; }
if (COMCode[11] == "1") { ErrorsReturn += "Temperatura troppo alta" + Environment.NewLine; }
if (COMCode[7] == "1") { ErrorsReturn += "Partial Format Flag" + Environment.NewLine; }
if (ErrorsReturn != System.String.Empty)
{
if (PrintTimerIsActive == true)
{
PrintTimer.Stop();
if (!ErrorTimer.Enabled)
ErrorTimer.Start();
MessageBox.Show(ErrorsReturn);
}
PrintTimerIsActive = false;
}
else
{
if (PrintTimerIsActive == false)
{
ErrorTimer.Stop();
PrintTimer.Start();
PrintTimerIsActive = true;
}
}
return ErrorsReturn;
}
private void SendFilesToCom(string filePath)
{
if (!_serialPort1.IsOpen)
{
try
{
_serialPort1.Open();
}
catch (Exception ex)
{
}
}
try
{
using (System.IO.TextReader reader = File.OpenText(filePath))
{
string line;
while ((line = reader.ReadLine()) != null)
{
_serialPort1.WriteLine(line);
}
HsCOMerrorStrings = _serialPort1.ReadLine();
reader.Close();
_serialPort1.Close();
}
}
catch (Exception ex)
{
}
}
}
}
My error
Cross-thread operation not
valid: Control 'MailTree' accessed
from a thread other than the thread it
was created on.
with my code
My idea is when SaveMail method has finish store 1 mes then add this mes to listview.
private delegate int SaveMailDelegate(ImapX.Message mes);
public int SaveMail(ImapX.Message mess)
{
if (!File.Exists("D:\\" + Username + "\\" + MailTree.SelectedNode.Text + "\\" + mes.MessageUid.ToString() + ".eml"))
{
mess.Process();
mess.SaveAsEmlToFile("D:\\" + Username + "\\" + MailTree.SelectedNode.Text + "\\", mes.MessageUid.ToString()); //Store messages to a Location
}
// mes.MessageUid=mess.MessageUid;
return 1;
}
Mime EncodingMail(string NodeName,string focusitem)
{
Mime m = new Mime();
m=Mime.Parse("D:\\" + Username+ "\\"+NodeName+"\\"+focusitem+".eml");
return m;
}
private void AddMesToMailList()
{
ListViewItem item = new ListViewItem();
Mime m = EncodingMail(MailTree.SelectedNode.Text, mes);
item.Text = mes.MessageUid.ToString();
item.SubItems.Add(m.MainEntity.Subject);
ReturnMime(m);
if (mailfromname != null)
item.SubItems.Add(mailfromname);
else item.SubItems.Add(mailfrom);
item.SubItems.Add(m.MainEntity.Date.ToString());
item.SubItems.Add(mailfrom);
MailList.Items.Add(item);
}
private void SaveMailDone(IAsyncResult iar)
{
SaveMailDelegate del = iar.AsyncState as SaveMailDelegate;
if (del != null)
{
int result = del.EndInvoke(iar);
AddMesToMailList();
}
}
private void MailTree_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)
{
MailList.Items.Clear();
for (int i = 0; i < client.Folders.Count; i++)
{
(ContextMenuListView.Items[1] as ToolStripMenuItem).DropDownItems[i].Click += new EventHandler(MainForm_Click);
}
if (MailTree.SelectedNode.Text == Username)
{
webBrowser1.Visible = false;//webBrowser1.DocumentText = "Hello Baby";
AttachmentList.Visible = false;
groupBox1.Visible = false;
}
else
{
webBrowser1.Visible = true;
groupBox1.Visible = true;
try
{
messages = client.Folders[MailTree.SelectedNode.Text].Search("ALL", false); // Search mail in your choossen Folder
AmoutOfMail = messages.Count(); //Amout of Mail in this Folder
for (int i = 0; i < AmoutOfMail; i++)
{
mes=messages[i];
SaveMailDelegate del = new SaveMailDelegate(this.SaveMail);
del.BeginInvoke(mes, new AsyncCallback(this.SaveMailDone), del);
}
}
catch (Exception)
{ }
}
}
You cannot directly access a control from another thread, you will have to invoke it.
private delegate void ControlCallback(string s);
public void CallControlMethod(string text)
{
if (control.InvokeRequired)
{
ControlCallback call = new ControlCallback((s) =>
{
// do control stuff
});
control.Invoke(call, new object[] { text });
}
else
{
// do control stuff
}
}
you can't access the UI on a different thread than what it was created on. From inside your secondary thread (the one that runs your callback handler) you will need to call Form.BeginInvoke to register a method that will be run on the UI thread. From that method you can update your UI controls
I think AddMesToMailList() is trying to modify the view elements but it is on a wrong thread.
Try something like this
void AddMesToMailList()
{
if (this.InvokeRequired)
{
this.BeginInvoke(new Action(AddMesToMailList));
return;
}
// do stuff that original AddMesToMailList() did.
}
EDIT:
SaveMail is a little complicated as it has a return value but you can try this
public int SaveMail(ImapX.Message mess)
{
if(this.InvokeRequired)
{
return (int) this.Invoke(
new Func<ImapX.Message, int>( m => SaveMail(mess)) );
}
else
{
if (!File.Exists(#"D:\" + Username + "\\" + MailTree.SelectedNode.Text + "\\" + mes.MessageUid.ToString() + ".eml"))
{
mess.Process();
mess.SaveAsEmlToFile(#"D:\" + Username + "\\" + MailTree.SelectedNode.Text + "\\", mes.MessageUid.ToString()); //Store messages to a Location
}
// mes.MessageUid=mess.MessageUid;
return 1;
}
}