public void processloader(object temp)
{
Process[] processes = null;
try
{
processes = Process.GetProcesses();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
Application.Exit();
return;
}
listView1.BeginUpdate();
listView1.Clear();
int threadscount = 0;
listView1.Items.Clear();
foreach (Process p in processes)
{
try
{
string[] prcdetails = new string[] { p.ProcessName, p.Id.ToString(), p.StartTime.ToShortTimeString(), p.PriorityClass.ToString(), (p.WorkingSet64 / 1048576).ToString() + "Mb", p.Threads.Count.ToString() };
ListViewItem proc = new ListViewItem(prcdetails);
listView1.Items.Add(proc);
threadscount += p.Threads.Count;
}
catch { Console.WriteLine(p); }
}
statusBar1.Panels[0].Text = "Processes : " + processes.Length.ToString();
statusBar1.Panels[1].Text = "Threads : " + (threadscount + 1).ToString();
listView1.EndUpdate();
listView1.Refresh();
}
here is the refreher block i call this function every second by using System.threading.timer(). i need a solution like original taskmanager refreshing functionality can anyone help for this? please provide some sample codes. thanks in advance!
use the below link helpful for your problem:
http://social.msdn.microsoft.com/Forums/eu/csharplanguage/thread/f8cb71ef-aba6-42f6-a462-533bca201d9e
Related
I have a program I have to finish which involves opening a file that has numbers, displaying it, then also displaying how many numbers the file has and the sum of them.
Im currently stuck on how to add all the numbers read and display it :/
Here is my code:
private void btnReadRandomNumbers_Click(object sender, EventArgs e)
{
StreamReader inputFile;
try
{
int number = 0;
int count = 0;
int sum = 0;
lstRandomNumbers.Items.Clear();
if (fodOpenFile.ShowDialog() == DialogResult.OK)
{
inputFile = File.OpenText(fodOpenFile.FileName);
lstRandomNumbers.Items.Clear();
while (!inputFile.EndOfStream)
{
number = int.Parse(inputFile.ReadLine());
count = count + 1;
lstRandomNumbers.Items.Add(number);
}
lblNumberCount.Text = count.ToString();
lblSumNumbers.Text = number.ToString();
}
}
catch (Exception ex)
{
MessageBox.Show("There is a problem with the disk file." + Environment.NewLine + ex.Message, "User Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
As seen in the Picture, the sum is only reading the last number of the list and im not sure why
Thanks for reading!
in line number = int.Parse(inputFile.ReadLine()); replaced number for each line!
you can write all code with this:
private void btnReadRandomNumbers_Click(object sender, EventArgs e)
{
try
{
lstRandomNumbers.Items.Clear();
if (fodOpenFile.ShowDialog() == DialogResult.OK)
{
var linesOfFile = File.ReadAllLines(fodOpenFile.FileName).Select(int.Parse).ToList();
lblSumNumbers.Text = linesOfFile.Sum().ToString();
lblNumberCount.Text = linesOfFile.Count().ToString();
lstRandomNumbers.DataSource = linesOfFile;
}
}
catch (Exception ex)
{
MessageBox.Show("There is a problem with the disk file." + Environment.NewLine + ex.Message, "User Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
You are almost there. Try your same code with minor modification. I have added inline comments.
private void btnReadRandomNumbers_Click(object sender, EventArgs e)
{
StreamReader inputFile;
try
{
int number = 0;
int count = 0;
int sum = 0;
//lstRandomNumbers.Items.Clear(); //don't need this
if (fodOpenFile.ShowDialog() == DialogResult.OK)
{
inputFile = File.OpenText(fodOpenFile.FileName);
//lstRandomNumbers.Items.Clear();//don't need this
while (!inputFile.EndOfStream)
{
number = int.Parse(inputFile.ReadLine());
count = count + 1;
//lstRandomNumbers.Items.Add(number);//don't need this
sum+=number; // add this
}
lblNumberCount.Text = count.ToString();
lblSumNumbers.Text = sum.ToString(); //change `number' to `sum`
}
}
catch (Exception ex)
{
MessageBox.Show("There is a problem with the disk file." + Environment.NewLine + ex.Message, "User Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
#Issa, Please let me know if this helps.
Give this a go:
private void btnReadRandomNumbers_Click(object sender, EventArgs e)
{
if (fodOpenFile.ShowDialog() == DialogResult.OK)
{
var lines = File.ReadAllLines(fodOpenFile.FileName);
var result =
lines
.Select(x => int.Parse(x))
.Aggregate(
new { count = 0, sum = 0 },
(a, x) => new { count = a.count + 1, sum = a.sum + x });
lstRandomNumbers.Items.Clear();
lstRandomNumbers.Items.AddRange(lines);
lblNumberCount.Text = result.count.ToString();
lblSumNumbers.Text = result.sum.ToString();
}
}
static void Main(string[] args)
{
var res = 0;
var r = new Regex(#"\d");// you can try "\d+" and you will see the difference
var matches = r.Matches("feawfwe312faewfa4gaeg1feaga67awfaw2");
if (matches != null && matches.Count > 0)
{
foreach (var m in matches)
res += int.Parse(m.ToString());
}
Console.WriteLine(res);
Console.ReadKey();
}
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.
Hi everyboy I have some problem with Multi Thread and ListView Update:
I want to list running process by name in a Listview, and removing when this process close. But my code just adding a new process and dont remove when the process close. I am a beginner user in C#. Thank you.
*** I dont want to use listview.Clear() cause Im going to make a bot with multi client
Here's my code:
bool status = true;
int[] PID = new int[10];
Memory Mem = new Memory();
private void startChecking()
{
while (status)
{
try
{
int count = 0;
Process[] processes = Process.GetProcessesByName("notepad");
if (processes.Length > 0)
{
if (listAccount.Items.Count < processes.Length)
{
foreach (Process process in processes)
{
if (listAccount.Items.Count < processes.Length && PID[count] != process.Id)
{
Mem.SetTitle(process.MainWindowHandle, "Cyber Auto - " + count.ToString());
AddItemNew(process.MainWindowTitle);
PID[count] = process.Id;
}
count++;
}
}
else if (listAccount.Items.Count < processes.Length)
{
}
}
Thread.Sleep(1000);
}
catch (Exception ex)
{
MessageBox.Show("Somethine went wrong : " + ex.ToString());
}
}
}
Here is my AddItemNew / RemoveItem methods:
private delegate void dlgAddItemNew(string i);
private void AddItemNew(string i)
{
if (this.listAccount.InvokeRequired)
{
this.Invoke(new dlgAddItemNew(AddItemNew), i);
}
else
{
ListViewItem accountAdd = new ListViewItem(i);
accountAdd.SubItems.Add("0");
accountAdd.SubItems.Add("0");
accountAdd.SubItems.Add("0");
accountAdd.SubItems.Add("0");
this.listAccount.Items.Add(accountAdd);
}
}
private delegate void dlgRemoveItem(int i);
private void RemoveItem(int i)
{
if (this.listAccount.InvokeRequired)
{
this.Invoke(new dlgRemoveItem(RemoveItem), i);
}
else
{
this.listAccount.Items[i].Remove();
}
}
P/S : Sorry If my Enlish is not good....
If you want to check at periodic interval, then you can clear the ListView before populating it again. (This is what Captain0 meant in his comments above)
I have modified your code a bit and I can see it working when I open/close instance of notepad, it update the count, No need for separate add/remove items (unless you had to something different in opening & closing of notepad process)
private void startChecking()
{
while (status)
{
try
{
Process[] processes = Process.GetProcessesByName("notepad");
UpdateListView(processes.Count());
Thread.Sleep(2000);
}
catch (Exception ex)
{
MessageBox.Show("Somethine went wrong : " + ex.ToString());
status = false;
}
}
}
private void UpdateListView(int processCount)
{
if (listView1.InvokeRequired)
{
Action action = () => UpdateListView(processCount);
Invoke(action);
}
else
{
listView1.Items.Clear(); // Clearing the List view before adding them again
for (int i = 0; i < processCount; i++)
{
ListViewItem accountAdd = new ListViewItem(i.ToString());
listView1.Items.Add(accountAdd);
}
}
}
Backgroundworker dowork event
string CurrentFileWithPath;
private void _FileProcessingWorker_DoWork(object sender, DoWorkEventArgs e)
{
try
{
DirectoryInfo[] MySubDirectories = (DirectoryInfo[])e.Argument;
for (int i = 0; i < MySubDirectories.GetLength(0); i++)
{
DirectoryInfo MySubDirectory = MySubDirectories[i];
List<FileInfo> l = new List<FileInfo>();
CountFiles(MySubDirectory, l);
int totalFiles = l.Count;
object[] CurrentStatus = new object[5];
CurrentStatus[3] = i.ToString();
CurrentStatus[4] = totalFiles.ToString();
_FileProcessingWorker.ReportProgress(0, CurrentStatus);
string CurrentDirectory = "Current Directory: " + MySubDirectory.Name;
foreach (FileInfo MyFile in l)
{
CurrentStatus = new object[5];
if (_FileProcessingWorker.CancellationPending)
{
e.Cancel = true;
return;
}
if (MyFile.Extension.ToLower() == ".cs" || MyFile.Extension.ToLower() == ".vb")
{
string CurrentFile = "Current File: " + MyFile.Name;
string CurrentFileWithPath = MyFile.FullName;
CurrentStatus[0] = CurrentDirectory;
CurrentStatus[1] = CurrentFile;
_FileProcessingWorker.ReportProgress(0, CurrentStatus);
List<string> Result = SearchInFile(CurrentFileWithPath, "static class FileShellExtension");
if (Result != null && Result.Count > 0)
{
CurrentStatus[2] = Result;
_FileProcessingWorker.ReportProgress(0, CurrentStatus);
}
}
}
}
}
catch (Exception err)
{
return;
}
Progresschanged event
private void _FileProcessingWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if (typeof(object[]) == e.UserState.GetType())
{
object[] StatusMsg = (object[])e.UserState;
if (5 == StatusMsg.GetLength(0))
{
label2.Text = StatusMsg[4].ToString();
label4.Text = StatusMsg[3].ToString();
if (StatusMsg[0] != null && StatusMsg[1] != null)
{
lblCurrentDirectory.Text = StatusMsg[0].ToString();
lblStatus.Text = StatusMsg[1].ToString();
}
if (StatusMsg[2] != null)
{
if (StatusMsg[2].GetType() == typeof(List<string>))
{
List<string> l = (List<string>)StatusMsg[2];
for (int i = 0; i < l.Count; i++)
{
ListViewCostumControl.lvnf.Items.Add("Directory: " + lblCurrentDirectory.Text + "In File: " + lblStatus.Text + l[i]);
w.WriteLine("Directory: " + lblCurrentDirectory.Text + "In File: " + lblStatus.Text + l[i]);
}
}
}
}
}
}
CountFiles method
private void CountFiles(DirectoryInfo di, List<FileInfo> l)
{
try
{
l.AddRange(di.EnumerateFiles());
}
catch
{
string fff = "";
}
try
{
IEnumerable<DirectoryInfo> subDirs = di.EnumerateDirectories();
if (subDirs.Count() > 0)
{
foreach (DirectoryInfo dir in subDirs)
CountFiles(dir, l);
}
}
catch
{
string yyy = "";
}
}
SearchInFile method
private List<string> SearchInFile(string fileToSearch, string textToSearch)
{
List<string> l = new List<string>();
try
{
foreach (var line in File.ReadAllLines(fileToSearch))
{
if (line.Contains(textToSearch))
l.Add(line);
}
}
catch(Exception err)
{
string fff = err.ToString();
}
return l;
}
The first problem is when getting the number of directories:
private void btnProcess_Click(object sender, EventArgs e)
{
btnProcess.Enabled = false;
btnDirectory.Enabled = false;
btnCancel.Visible = true;
btnCancel.Enabled = true;
btnCancel.Text = "Cancel";
MyProgressBar.Visible = true;
_FileProcessingWorker = new BackgroundWorker();
_FileProcessingWorker.WorkerReportsProgress = true;
_FileProcessingWorker.WorkerSupportsCancellation = true;
_FileProcessingWorker.DoWork += new DoWorkEventHandler(_FileProcessingWorker_DoWork);
_FileProcessingWorker.ProgressChanged += new ProgressChangedEventHandler(_FileProcessingWorker_ProgressChanged);
_FileProcessingWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(_FileProcessingWorker_RunWorkerCompleted);
string BasePath = lblDirectoryName.Text;
DirectoryInfo MyDirectory = new DirectoryInfo(BasePath);
DirectoryInfo[] MySubDirectories = MyDirectory.GetDirectories();
int SubDirectoryCount = MySubDirectories.GetLength(0);
MyProgressBar.Minimum = 0;
MyProgressBar.Step = 1;
MyProgressBar.Maximum = SubDirectoryCount;
MyProgressBar.Value = MyProgressBar.Minimum;
_LastCounter = 0;
_FileProcessingWorker.RunWorkerAsync(MySubDirectories);
}
In the click button i'm getting the sub directories.
But there are two problems.
In the dowork event when i put a break point on this line:
for (int i = 0; i < MySubDirectories.GetLength(0); i++)
I see that it contain 409 directories. But when i report the number of directories to the label4 in the dowork event
CurrentStatus[3] = i.ToString();
In the progresschanged event
label4.Text = StatusMsg[3].ToString();
I see in the end on label4 408 directories. And in D:(in this case i'm working on my D:\ directory) when i select all the directories in windows explorer make right click and properties i see only 405 directories. So what is the real number of directories ? What and how number of directories should i display in label4 ?
The second problem is when i report the number of files in dowork event:
CurrentStatus[4] = totalFiles.ToString();
And in progresschanged event show it on label2:
label2.Text = StatusMsg[4].ToString();
The problem is that the totalFiles value is changing all the time once it's 2 then it's 768 then it's 66 then 8987 but what i want to do is somehow to sum in real time the values in totalFiles so in label2 i will see first time for example: 2 then 770 then (770+66) so i will see in label2 816....to see always the sum of all the values so far.
The last problem is in the progresschanged event this loop:
for (int i = 0; i < l.Count; i++)
{ ListViewCostumControl.lvnf.Items.Add("Directory: " + lblCurrentDirectory.Text + "In File: " + lblStatus.Text + l[i]);
w.WriteLine("Directory: " + lblCurrentDirectory.Text + "In File: " + lblStatus.Text + l[i]);
}
It might be logic somehow to take out and make this loop at this time in the program in another backgroundworker like backgroundworker2 dowork event ? If so how to do it ? The problem is when the loop have many items to add to the listView it make the program to hang until the loop finish.
Each time you execute
CurrentStatus[4] = totalFiles.ToString();
You are resetting the status value to the count of files in the current processing directory. This is why the number keeps bouncing around. Instead I would suggest:
int thisDirFiles;
thisDirFiles = l.Count;
totalFiles += thisDirFiles;
CurrentStatus[4] = totalFiles.ToString();
Now when you report progress, CurrentStatus[4] will have the running total.
For your second question, it looks to me you are trying to do too much when you are reporting progress. Manipulating ListViews can be costly, and you are probably spending more time updating the ListView than you are processing the directories, so your machine seems to freeze.
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;
}
}