Question Convert Console code into a form application?

SamiN

New member
Joined
Sep 6, 2020
Messages
4
Programming Experience
Beginner
Hello, I was looking for a code can get the names of all opened windows and got this one:
C#:
using System.Diagnostics;

Process[] processlist = Process.GetProcesses();

foreach (Process process in processlist)
{
    if (!String.IsNullOrEmpty(process.MainWindowTitle))
    {
        Console.WriteLine("Process: {0} ID: {1} Window title: {2}", process.ProcessName, process.Id, process.MainWindowTitle);
    }
}
this code works perfectly but l need to show the result of the console into the form, I ask if the code can be added to or converted into a code under a button in c# windows form application.
 
Last edited:
You're basically asking us how to display text in a Windows Forms application. I find it hard to believe that you looked for information on how to do that and found none. There are numerous ways to combine multiple Strings into one and display them so a bit of research should turn up at least one option, if not several. I suggest that you do a bit of research, try to implement something and then post back and show us what you did if it doesn't work. One of those many options would involve a StringBuilder, so maybe you should look into that.
 
Also, if you are just at the beginning stages of learning, lean towards learning something that will have long term impact. WinForms is at end of life. Pick WPF, Xamarin, or UWP instead which are more current, and have concepts and approaches that extend to other frameworks.
 
There are numerous ways to combine multiple Strings into one and display them
thank you, yesterday I tried many things but I didn't get the correct route, but your hint hit the nail on the head.

WinForms is at end of life
Technology is similar to mirage when someone thought he reached it he discover it had moved to another place.

the code after editing:

C#:
private void Btn1_Click(object sender, EventArgs e)
        {
            Process[] processlist = Process.GetProcesses();
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            foreach (Process process in processlist)
            {
                if (!String.IsNullOrEmpty(process.MainWindowTitle))
                {             
                    sb.Append(("Process: {0} ID: {1} Window title: {2}", process.ProcessName, process.Id, process.MainWindowTitle));
         
                    Rtxt1.Text = sb.ToString();
                }
            }
        }
 
Last edited:
Move line 11 out of the loop, only the end result will be seen.
 
I applied your hint but nothing changed every thing goes well before and after editing.
Something did change but you just can't see it because it happens too fast. With the code you had, you were displaying the current text each time you added a line to it. That's pointless because you only want the final text after adding all the parts. By moving that line you don't keep displaying incomplete text over and over before displaying the final text; you just display the final text when it's ready. Your original code produced the desired result but it did it in a suboptimal way. That is why you need to have a clear understanding of what your code needs to do, i.e. have an algorithm to implement. If you did that then you would never have a step in your algorithm to display part of the text over and over. You would just display it once at the end, so that's what your code should do.
 
Last edited:
You really shouldn't be updating your UI like that.

  • Move to WPF, and skip Winforms, since Winforms is EOL. You should be using WPF or Xamarin.
  • You should be using a model to control and update your UI.
  • Lack of using a model will mean you are currently and incorrectly updating your UI. However small your operation is, you shouldn't be running operations in buttons or other controls part of your UI. That's why we use views and models.
  • By not using a model, you need alternative ways to update your UI. For those who don't like dabbling with views; they often prefer using threads and tasks instead. And while this is Ok, It's not the recommended approach. Views and models are.
However; if you want to simply update your UI, and not have it hanging while it finds all open processes (which it will if their are loads open.) You can use this example code, on how to use threading and tasks to update your UI while performing lengthily operations. While this will also do as you want, and more efficiently. There is still a lot of room for improvements, such as adding using blocks to the tasks, however, you should also be careful doing that, as a using block may also try to dispose of a task which hasn't finished running yet, and that will result in an exception been thrown. There are a lot of modifications you can improve on here, but if you are really interested in going this route instead of WPF and the whole views and models approach, then try searching for keywords such as threading, multithreading, and search by my username. I've answered these questions many times before and I have provided a lot of examples in the past.

Here is the code :
C#:
        internal static List<Process> processlist = new List<Process>();
        internal delegate void Delegate_Callback_To(string itm_Value, Control control, bool visibility);
        public void UpdateUI_With_NewItem(string value, Control control, bool visibility)
        {
            control.Text = value;
            control.Visible = visibility;
        }
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            Task Task_UpdateLabel = new Task(() => UpdateLabel("Please wait while we search for open programs", label1, true));
            Task_UpdateLabel.Start();

            Task FindProcess = new Task(() => GetProcesses());
            FindProcess.Start();
        }
        internal void UpdateLabel(string ui_Message, Control control, bool visible) => Rtxt1.Invoke(new Delegate_Callback_To(UpdateUI_With_NewItem), ui_Message, control, visible);
        internal List<Process> GetProcesses()
        {
            processlist.AddRange(Process.GetProcesses().Where(process => !string.IsNullOrEmpty(process.MainWindowTitle)));
            Task WithProcessList = new Task(() => WithProcesses(processlist));
            WithProcessList.Start();
            WithProcessList.Wait();
            return processlist;
        }
        internal void WithProcesses(List<Process> processes)
        {
            StringBuilder builder = new StringBuilder();
            processes.ForEach((Process current_Process) => builder.AppendLine($"Process: {current_Process.ProcessName} ID: {current_Process.Id} Window title: {current_Process.MainWindowTitle}"));
            Rtxt1.Invoke(new Delegate_Callback_To(UpdateUI_With_NewItem), builder.ToString(), Rtxt1, true);
            label1.Invoke(new Delegate_Callback_To(UpdateUI_With_NewItem), "", label1, false);
        }

Some example screenshots of it in action. I also added label1 to display a message to the user while the tasks are running, and once completed the label is set advisable. Feel free to make improvements, and share them here if you wish.

Beginning : Screenshot
Ending : Screenshot
 
Back
Top Bottom