Closing Processes represented by CheckedItems in c# - c#

I am wanting to close processes that a user selects in a ListView box in another form. the ListView box uses checkboxes for selecting which processes to close. Unfortunately, i dont know how to convert the checked processes into processes....any help?
public void Form4_Load(object sender, EventArgs e)
{
Process[] prs = Process.GetProcesses();
listView1.Items.Clear();
foreach (Process proces in prs)
{
if (!string.IsNullOrEmpty(proces.MainWindowTitle))
listView1.Items.Add(proces.MainWindowTitle);
}
foreach (Process PRC in listView1.CheckedItems)
{
\\Idk what to put here.
}

In order to kill a process you either need it's name or process id, so change your above code that adds process to ListView1 to some thing like this:
private void Form4_Load(object sender, EventArgs e)
{
Process[] prs = Process.GetProcesses();
listView1.Items.Clear();
foreach (Process proces in prs)
{
if (!string.IsNullOrEmpty(proces.MainWindowTitle))
{
ListViewItem item = new ListViewItem();
item.Tag = proces.Id; //it will be used to kill this process
item.Text = proces.MainWindowTitle;
listView1.Items.Add(item);
}
}
}
Note the tag field, which we will use later to kill the selected process.. Now loop through all selected ListViewItems, get the corresponding process id from tag field and get the reference to the process using System.Diagnostics.Process.GetProcessById. This method returns an object of Process, which exposes a Kill method using which one can stop the process this object refers to.
private void button1_Click(object sender, EventArgs e)
{
foreach (ListViewItem list in listView1.CheckedItems)
{
Process p = System.Diagnostics.Process.GetProcessById(Convert.ToInt32(list.Tag));
if (p != null)
p.Kill();
}
}

Related

Execute And Close Other Applications From My Winform C#

It is a small part of my program where my program needs to start the program from DataGridView (Content Clicked Event) and its just executing that program perfectly but is not able to close it because some of incoming programs don't have same process name as file name. I tried getting processid too but it throws following error (can you please provide me a working code because i can get the id of my winform process but how can i get the processid of externally launched app from my program.
i tried it it throws the following error
An unhandled exception of type 'System.ArgumentException' occurred in System.dll
Additional information: Process with an Id of 16924 is not running.)"
the code in which i am getting process id but fails is below
private void button1_Click(object sender, EventArgs e)
{
var processid = Process.Start("Calc");
pn =processid.ProcessName;
pid = processid.Id;
}
int pid;
String pn;
private void button2_Click(object sender, EventArgs e)
{
var process1 = Process.GetProcessById(pid);
process1.Kill();
}
The dummy code is below.
I have already tried:
private void button1_Click(object sender, EventArgs e)
{
Process.Start("Calc");
}
private void button2_Click(object sender, EventArgs e)
{
foreach (var process in Process.GetProcessesByName("Calc"))
{
process.Kill();
}
}
My Code:
private void button1_Click(object sender, EventArgs e)
{
Process.Start("THIS PATH WILL COME FROM DATABASE");
}
private void button2_Click(object sender, EventArgs e)
{
foreach (var process in Process.GetProcessesByName("PROCESS NAME WHICH MY PROGRAM STARTED"))
{
process.Kill();
}
}
When you start the process get the Id of the process, and store it. You can then get the process by id to kill it. This not only ensures you don't need to know the name of the process (in case it's different from the path to start it) but ensures that you kill the correct instance if there are multiple instances running, some of which weren't started by your program.

Text_Changed problems

Hello i have a search box, that is a TextBox, that filters the ListBox.
I have an array of items and the code does next thing:
private async void SearchTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
ListBox.Items.Clear();
foreach (Item a in arr)
{
if(a.Title.Contains(SearchTextBox.Text))
{
ListBox.Items.Add(a);
}
}
}
All works fine when i delete by 1 symbol, but when i hold backspace something strange happens, items start to duplicate or change their positions - what is the problem and how to prevent this?
You are likely re-entering the handler on the same thread (the UI thread) while you are looping. One option is to detach the handler upon entry and then reattach on exit. You will probably need to do a double check then that nothing else happened while you had it detached.
I am not as familiar with Window 8 apps, but filtering a ListBox based on a TextBox is very common. I would expect you to be able to use something like CollectionViewSource.Filter to do the filtering automatically (see this question for an example).
A basic implementation:
private void SearchTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
string initialText = SearchTextBox.Text;
SearchTextBox.TextChanged -= SearchTextBox_TextChanged;
do
{
ListBox.Items.Clear();
foreach (Item a in arr)
{
if(a.Title.Contains(initialText))
{
ListBox.Items.Add(a);
}
}
} while (SearchTextBox.Text != initialText)
SearchTextBox.TextChanged += SearchTextBox_TextChanged;
}
Ok, I see this is async, you need to synchronize this method
Create an instance object named _syncRoot:
private object _syncRoot = new Object();
private async void SearchTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
lock( _syncRoot)
{
ListBox.Items.Clear();
foreach (Item a in arr)
{
if(a.Title.Contains(SearchTextBox.Text))
{
ListBox.Items.Add(a);
}
}
}
}

Live update of TreeView while populating in background thread

Topic says it all , here it is code i have right now :
public void StartCDA()
{
backgroundWorker1.RunWorkerAsync();
}
public delegate void AddCDAnode(DirectoryInfo dirinfo);
public void ListDirectory(DirectoryInfo path)
{
ImagesTV.Nodes.Add(CreateDirectoryNode(path));
}
public void Addnode(DirectoryInfo dirinfo)
{
Invoke(new AddCDAnode(ListDirectory), new object[] {dirinfo});
}
private TreeNode CreateDirectoryNode(DirectoryInfo directoryInfo)
{
var directoryNode = new TreeNode(directoryInfo.Name);
foreach (var directory in directoryInfo.GetDirectories())
{
Statustext = directory.FullName;
directoryNode.Nodes.Add(CreateDirectoryNode(directory));
}
foreach (var file in directoryInfo.GetFiles())
directoryNode.Nodes.Add(new TreeNode(file.Name));
return directoryNode;
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
Addnode(CdaDir);
}
Right now problem is that actually Treeview is not being populated in background and that's pretty strange as i am using background worker for that. But the main problem is that here i have kind of image viewer (form is splitted in two parts, left is treeview and right is picture preview box) and list of images to view sometime contains about 1000 elements , that's why i need to be able to see "live" update of treeview , while being able to go through items and view images. There will be no ability to delete , move or somehow affect Treeview , the only action is to click through tree.
Thanks.

get particular serialport information by changing the port value using C#

I have written the following code in form load event. When the form is getting loaded the available serialports are added into the combobox.
String[] ports = SerialPort.GetPortNames();
private void Form1_Load(object sender, EventArgs e)
{
_serialPort = new SerialPort();
foreach (string port in ports)
{
cbox.Items.Add(port);
}
}
In the next step,in combobox selectedindex_changed event,when am changing the port, the port details are updated in multiline textbox.
private void cbox_SelectedIndexChanged(object sender, EventArgs e)
{
using (var searcher = new ManagementObjectSearcher("SELECT * FROM WIN32_SerialPort"))
{
var prts = searcher.Get().Cast<ManagementBaseObject>().ToList();
var tList = (from n in ports
join p in prts on n equals p["DeviceID"].ToString()
select n + " - " + p["Caption"]).ToList();
foreach (string s in tList)
{
mtxt.AppendText(s); // multiline textbox
}
}
}
For example:
In this program, ports are added into combo box from (COM3 to comX).
But my problem is whatever the port i select, it returns only the details of 1st port from the combobox (i.e. it return only the details of COM3).Pls any one help me for getting details of port which i select in combobox.
Follow discussion over here
http://social.msdn.microsoft.com/Forums/en-US/winformsdesigner/thread/c236cac4-a954-4a70-882d-bc20e2cc6e81
Read Following in that
We can't get the information through the SerialPort type. I don't know
why you need this info in your application. However, there's a solved
thread with the same question as you. You can check out the code
there, and see if it can help you.

How to kill a Windows Process through a WPF ListView?

I am a WPF newbee trying to build my own Windows Task Manager.
Right now i have a window with all the active processes running on my machine showing in a ListView.
Now here is my problem: I have a button called End Process. I want to select a process from the ListView and kill it by pressing the End Process button. I just cant figure it out how to do that.
I have this code (C#) assigned to the button:
private void End_Process_Click(object sender, RoutedEventArgs e)
{
Process[] procs=Process.GetProcessesByName(ProcessesListView.SelectedItem.ToString());
foreach (Process p in procs)
{
p.Kill();
}
}
I suspect the items in your list are the actual Process objects. If so, you can do something like this:
private void End_Process_Click(object sender, RoutedEventArgs e)
{
Process process = (Process)ProcessesListView.SelectedItem;
process.Kill();
}

Categories