WildBamaBoy 19 Junior Poster

AM and PM have nothing to do with it, say you have a timespan of 37 hours 15 minutes and and 13 seconds. Would that be AM or PM?
I think this is about hours worked, right?

He was telling me how my idea wouldn't work. :P

If you're going AM to AM I did the same thing just without converting to military hour. However I believe it does have a problem with PM to AM, but it worked for my needs how it was so I didn't bother to fix it. Not the best thing for you then.

WildBamaBoy 19 Junior Poster

Hey! I've done something exactly like this before! :)

DateTime and TimeSpan didn't work so well for me and required extra crap like Days, Year, Seconds, etc. I didn't like that. I only wanted the distance between two hours in one day. What I ended up doing was, if the time was a PM time, I converted that to military hours and subtracted from the start time.

For example:
Start Time = 5:00am
End Time = 2:00pm

2pm Military Time = 14:00. So I did 14 - 5 and 0 - 0, which gives me 9.

It'll get a bit more involved if the time isn't right on the hour. Minutes will tend to be wacked up, but there's an easy workaround. I have code if you want it.

WildBamaBoy 19 Junior Poster

Right now I only need to be able to send a 100kb JPEG photo. I tried Google and found a couple of things but their code only threw exceptions so maybe what they've done is not appropriate in my situation.

This is an attempt at a remote screen viewer. If you're sharing your screen, I start a TcpListener on a random port and display the IP the viewer must use to connect to you. If you're a viewer, you type in the IP and port you want and it sends a request to connect by TcpClient.

That's all I've got to. Here's some code.

Connecting to a client:

private TcpClient MasterConnectionClient = new TcpClient();

private void ConnectButton_Click(object sender, EventArgs e)
        {
            string[] ConnectionInfo = ConnectToIPAddressBox.Text.Split(':');

            try
            {
                MasterConnectionClient.Connect(IPAddress.Parse(ConnectionInfo[0]), int.Parse(ConnectionInfo[1]));

                ViewportForm VPF = new ViewportForm();
                this.Hide();

                VPF.ShowDialog(); //Shows the form that will display the screenshot
            }

            catch (Exception E)
            {
                MessageBox.Show(E.Message, E.GetType().ToString());
            }

Client waiting for connection

int Port = new Random().Next(1, 65535);

            ClientSide.MasterListener = new TcpListener(IPAddress.Any, Port);
            ConnectionAddressLabel.Text = GetExternalIP() + ":" + Port.ToString();
        
private void ShareButton_Click(object sender, EventArgs e)
        {
            CurrentOperationLabel.Text = "Waiting for connection...";

            new Thread(new ThreadStart(
                delegate
                {
                    ClientSide.MasterListener.Start();
                    ClientSide.MasterSocket = ClientSide.MasterListener.AcceptSocket();

                    ScreenViewerIPLabel.Invoke(new ThreadStart(
                            delegate
                            {
                                ScreenViewerIPLabel.Text = ClientSide.MasterSocket.RemoteEndPoint.ToString();
                            }));
                })).Start();
        }

And this is what I've picked out from Google on getting and sending the screenshot. I don't understand line 12 and down. It throws an exception that says "A request to send or receive data was disallowed because the socket …

WildBamaBoy 19 Junior Poster

You can set a control's location and many other properties from within the code. What you want to do would be done like so, and other properties can be set in a similar way.

ButtonName.Location = new Point(X, Y);

I'd put this in the constructor, after InitializeComponent();, so that it runs when the program is started.

WildBamaBoy 19 Junior Poster

Perfect! :) Works exactly like I wanted it to.

WildBamaBoy 19 Junior Poster

I want to start a method whose name is in a string. My server program will be receiving commands from the client, perform those commands, and send the information back to the client. So instead of using a switch with many cases that only execute a method, I thought it would be easier just to send the method name from the client and the server run that method. Google turned up sections of the code below, but it does not work.

Here's what I want to happen.

string MethodName = Receive(); //Gets a string from client, this case it's "Help"
            try
            {
                Commands.Execute(MethodName);
            }

            catch
            {
                Log("No method with the name '" + MethodName + "' exists.");
            }

Here is my Commands class. The Execute code is what I picked up from Google. info always turns up being null, and I don't understand this code anyway so I'm not sure what to do. Is this even the right way to do it?

public static class Commands
    {
        public static void Execute(string CommandName)
        {
            Random rand = new Random();

            System.Reflection.MethodInfo info = rand.GetType().GetMethod(CommandName);
            double r = (double)info.Invoke(rand, null);
        }

        public static void Help()
        {
            Server.Send("BLAH"); //Client will recieve "BLAH" and display it on screen
        }
        // further list of commands

    }
WildBamaBoy 19 Junior Poster

I have a group with 7 different NumericUpDown boxes in it. Above those I have a label that tells how many choices you have remaining. When the NumericUpDown goes up, the remainder goes down. However it also goes down when a NumericUpDown goes down as well. It needs to go UP when a choice goes down. I don't see any method or event that tells if the value went up or down. How could I implement this?

WildBamaBoy 19 Junior Poster

Oh wow. Yup, that appears to be it. That is very weird...

Solved. Thank you

WildBamaBoy 19 Junior Poster

Ah. Gotcha. Same result. :'( It keeps highlighting the second foreach. ( foreach (object ListedProcess in PC_ProcessList.Items) )

WildBamaBoy 19 Junior Poster

Lock it? It doesn't have a method called Lock or Unlock.

WildBamaBoy 19 Junior Poster

Nope...I got the same exception at the same place.

WildBamaBoy 19 Junior Poster

Your second method is what you need to do, not sure why you got an error you'll have to post your code.

Exactly...that puzzled me too. Here's the code using lists. The last bit is the only time something is added or removed from the list box.

private static void UpdateProcessList(ListBox PC_ProcessList)
        {
            while (true)
            {
                List<string> NamesToAdd = new List<string>();
                List<string> NamesToRemove = new List<string>();

                if (PC_ProcessList.IsHandleCreated)
                {
                    PC_ProcessList.Invoke(new ThreadStart(
                        delegate
                        {
                            foreach (Process RunningProcess in Process.GetProcesses())
                            {
                                if (!PC_ProcessList.Items.Contains(RunningProcess.ProcessName))
                                {
                                    NamesToAdd.Add(RunningProcess.ProcessName);
                                }
                            }

                            foreach (object ListedProcess in PC_ProcessList.Items)
                            {
                                if (ReturnProcessInstance(Process.GetProcessesByName(ListedProcess.ToString())) == null)
                                {
                                    try
                                    {
                                        PC_ProcessList.SelectedIndex = PC_ProcessList.SelectedIndex - 1;
                                    }

                                    catch (ArgumentOutOfRangeException)
                                    {
                                        PC_ProcessList.SelectedIndex = PC_ProcessList.SelectedIndex + 1;
                                    }

                                    NamesToRemove.Add(ListedProcess.ToString());
                                }
                            }

                            foreach (string name in NamesToAdd)
                            {
                                PC_ProcessList.Items.Add(name);
                            }

                            foreach (object name in NamesToRemove)
                            {
                                PC_ProcessList.Items.Remove(name);
                            }

                        }));
                }

                Thread.Sleep(500);
            }
        }
WildBamaBoy 19 Junior Poster

This list box will contain the name of processes that are currently running. My function to update the list first checks to see if it does not contain the name of a process that is running, then adds the process if it needs to. Then it checks to see if it contains a process that is no longer running, and then it will remove the process.

Here is the code:

private static void UpdateProcessList(ListBox PC_ProcessList)
        {
            while (true)
            {
                if (PC_ProcessList.IsHandleCreated)
                {
                    PC_ProcessList.Invoke(new ThreadStart(
                        delegate
                        {
                            foreach (Process RunningProcess in Process.GetProcesses())
                            {
                                if (!PC_ProcessList.Items.Contains(RunningProcess.ProcessName))
                                {
                                    PC_ProcessList.Items.Add(RunningProcess.ProcessName);
                                }
                            }

                            foreach (object ListedProcess in PC_ProcessList.Items)
                            {
                                if (ReturnProcessInstance(Process.GetProcessesByName(ListedProcess.ToString())) == null)
                                {
                                    try
                                    {
                                        PC_ProcessList.SelectedIndex = PC_ProcessList.SelectedIndex - 1;
                                    }

                                    catch (ArgumentOutOfRangeException)
                                    {
                                        PC_ProcessList.SelectedIndex = PC_ProcessList.SelectedIndex + 1;
                                    }

                                    PC_ProcessList.Items.Remove(ListedProcess);
                                }
                            }
                        }));
                }

                Thread.Sleep(500);
            }
        }

It's throwing an InvalidOperationException when I remove a process from the list. It says "List that this enumerator is bound to has been modified. An enumerator can only be used if the list does not change." And it highlights line 18. Doesn't that mean that the list is modified by something else other than the current foreach block?

I tried to work around it by making two lists of strings and put the names to be added and names to be removed into them, THEN updating the list after both foreach blocks run but it still gave me the InvalidOperationException. I don't think I understand this exception correctly. ;)

WildBamaBoy 19 Junior Poster

Finally got this to work. I found a different way to make it close completely without starting another thread that opens my main form.

I think I'll stay away from threads for now on. Very irritating! Thank you both.

WildBamaBoy 19 Junior Poster

[STAThreadAttribute] doesn't do anything either.

Maybe it would be better to find a different way to open the second form...I'm not quite sure how to use the debugging tools or what I'm supposed to be looking for.

WildBamaBoy 19 Junior Poster

Thank you for the advice and I agree they are very unforgiving.

Check the ThreadState and see what it is.

It says "Running"...

Maybe this is just a case of not doing it right. ;) Have I put [STAThread] in the right place? This is my first form which asks for a password, then closes and opens my main form in another thread.

using System;
using System.Threading;
using System.Windows.Forms;
using System.Security.Cryptography;
using System.Text;

namespace CRT
{
    public partial class SecurityForm : Form
    {
        public SecurityForm()
        {
            InitializeComponent();
        }

        [STAThread] //<--------------------------//
        static void MainFormThread()
        {
            Application.Run(new MainForm());
        }

        private string GetMD5Hash(string input)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            byte[] a_byte = Encoding.UTF8.GetBytes(input);

            a_byte = md5.ComputeHash(a_byte);
            System.Text.StringBuilder SB = new System.Text.StringBuilder();

            foreach (byte b in a_byte)
            {
                SB.Append(b.ToString("x2").ToLower());
            }

            return SB.ToString();
        }

        private void PasswordBox_TextChanged(object sender, EventArgs e)
        {
            if (GetMD5Hash(PasswordBox.Text) == //md5 hash)
            {
                RightWrongImage.Image = Properties.Resources.Check_Mark;
                this.Refresh();

                Thread.Sleep(500);

                Thread MainThread = new System.Threading.Thread(new System.Threading.ThreadStart(MainFormThread));
                MainThread.Start();

                this.Close();
            }
        }
    }
}
WildBamaBoy 19 Junior Poster

Sure did. It still gives me that error. :confused:

WildBamaBoy 19 Junior Poster

Another weird problem now. I'm trying to open an OpenFileDialog on my second form but I'm getting a ThreadStateException. It says:

"Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThreadAttribute marked on it. This exception is only raised if a debugger is attached to the process."

Like it says, it works fine if I build it and run it outside of VS, but is it okay to just leave it with that exception?

WildBamaBoy 19 Junior Poster

I don't know how to use that but it looks like I figured it out. It looks like it was the way I showed the second form (my main part of the program). Instead of what I did above, I made a new thread that did Application.Run(new MainForm()); , started it from my password form, and then used this.Close() on my password form. Maybe it was staying alive because the password form was just hidden before?

WildBamaBoy 19 Junior Poster

Everyone else stumped, too? :'(

WildBamaBoy 19 Junior Poster

Huh...but if it's not the Background Workers what on earth could be keeping it from closing??? :?:

There's quite a bit of code...For now I'm just going to show what happens when it starts and then the background workers. Note that I combined 2 workers, so there's 4 now.

First Form. It runs when the program is started and asks for a password.

using System;
using System.Threading;
using System.Windows.Forms;
using System.Security.Cryptography;
using System.Text;

namespace WBB_CRT
{
    public partial class SecurityForm : Form
    {
        public SecurityForm()
        {
            InitializeComponent();
        }

        private string GetMD5Hash(string input)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            byte[] a_byte = Encoding.UTF8.GetBytes(input);

            a_byte = md5.ComputeHash(a_byte);
            System.Text.StringBuilder SB = new System.Text.StringBuilder();

            foreach (byte b in a_byte)
            {
                SB.Append(b.ToString("x2").ToLower());
            }

            return SB.ToString();
        }

        private void PasswordBox_TextChanged(object sender, EventArgs e)
        {
            if (GetMD5Hash(PasswordBox.Text) == //Specific MD5 Hash)
            {
                RightWrongImage.Image = Properties.Resources.Check_Mark;
                this.Refresh();

                Thread.Sleep(500);
                this.Hide();

                MainForm MainForm = new MainForm(); 
                MainForm.Show();   //Show the main program
            }
        }
    }
}

My MainForm initialization. All of my workers are on the main form

public MainForm()
        {
            InitializeComponent();
            
            //Irrelevant code

            UpdateProcessList.RunWorkerAsync();
            SetRunningBox.RunWorkerAsync();
            SetBlockedBox.RunWorkerAsync();
        }

Background worker 1

private void SetRunningBox_DoWork(object sender, DoWorkEventArgs e)
        {
            while (true)
            {
                bool Running = false;

                foreach (Process process in Process.GetProcesses())
                {
                    if (process.ProcessName == ProcessController.BadProcess)
                    {
                        Running = true;

                        if (RunningBox.Checked == false)
                        {
                            RunningBox.Invoke(new ThreadStart(
                                delegate
                                {
                                    RunningBox.Checked = true;
                                    RemoveBtn.Enabled = false;
                                    StartBtn.Enabled = false;
                                }));
                        }
                    }
                }

                if (Running == false)
                {
                    if (RunningBox.Checked == true)
                    {
                        RunningBox.Invoke(new ThreadStart(
                            delegate
                            {
                                RunningBox.Checked …
WildBamaBoy 19 Junior Poster

Oups..I'm working with Background Workers not Threads, I call them both threads. My bad. :D

WildBamaBoy 19 Junior Poster

My program starts 5 different threads when it is opened. One or more of them is not stopping correctly and is causing my program to remain alive even after the main form has closed. Before I go through trying to find which one is doing it is there some way I can just force every thread to immediately stop when the program is starting to close? I know it's bad technique to force something to stop but none of the threads are actually doing anything that could hurt if it's interrupted. All of them check each second to see if they need to do something so most of the time they're doing nothing at all.

WildBamaBoy 19 Junior Poster

Can anyone help? I'm still stuck on this.

WildBamaBoy 19 Junior Poster

I couldn't find anything that would do what I am trying to do with my client and server.

Mainly, I want to click a button that will start downloading a file I select on the remote computer. Optionally I would also like to show the transfer rate, estimate time remaining, and a progress bar.

The only thing I can find is how to download from a website, but I'm working with a remote computer running my server program. Is there some function to automatically do this? If there isn't how could I write it?

WildBamaBoy 19 Junior Poster

Wow. All great answers! Thanks.

WildBamaBoy 19 Junior Poster

I'm learning C++ and just finished a tutorial on pointers. I understood what they were and how to use them but I do not understand when they should be used. When would it be practical to use a pointer to get a value instead of using the value's name?

For example, why would I ever use pointers and do this:

#include <iostream>

using namespace std;

int main()
{
    int x;
    int *pnt_x;

    pnt_x = &x;

    cout << "Enter a number: ";
    cin >> x;

    cout << "You entered: " << *pnt_x;

    return 0;
}

Instead of this, which is the same thing but much simpler.

#include <iostream>

using namespace std;

int main()
{
    int x;

    cout << "Enter a number: ";
    cin >> x;

    cout << "You entered: " << x;

    return 0;
}
WildBamaBoy 19 Junior Poster

Thank you. I got it working.

WildBamaBoy 19 Junior Poster

Just as the title says, how can I detect double clicking in a ListView? I'm trying to emulate browsing through a directory with windows explorer.

WildBamaBoy 19 Junior Poster

I'm very sorry that my first post didn't help.

You need to use the atexit module. Here's a link to it in the Python documentation.
http://docs.python.org/library/atexit.html#module-atexit

There's some examples there too but they tend to be a bit advanced if you've just started learning. If you need any help, I promise I won't be confusing next time. :P

WildBamaBoy 19 Junior Poster

Thank you. Both programs finally work how I want now.

WildBamaBoy 19 Junior Poster

Whatever I did it works now...I need to do one more thing until I'm done with it. When my client requests to connect to the server, how can I get the IP Address of the computer the request is coming from?

WildBamaBoy 19 Junior Poster

I don't believe Python can do that to the console. You might be able to achieve something like this using some GUI toolkit like wxPython or tkinter.

But if you don't want to do that a possible workaround would be to write another small script to run alongside your main program and start it again if the questions have not been answered. You wouldn't want this secondary program to have a window either, so you should save it as a .pyw file when it is working.

A very sloppy example:

import os
import time

AllQuestionsCorrect = False #Set this to true from the main program when it needs to be

while (AllQuestionsCorrect == False): #do this over and over while AllQuestionsCorrect is false
    time.sleep(0.5) # Sleep a little to avoid 100 percent processor usage

    # --- Check if main program is running ---

    if (NotRunning):
        os.system("main program directory")

If you want to do this you'll need to download a third party module. Python doesn't have a built-in way to check running processes in Windows. WMI seems like it will do the job.

Here's a link to its download page: http://timgolden.me.uk/python/wmi/index.html
And here are some useful examples: http://tgolden.sc.sabren.com/python/wmi/cookbook.html#running_processes

WildBamaBoy 19 Junior Poster

I believe so. When I first ran the server Windows Firewall asked me if I wanted to unblock it, and I did. I'm completely rewriting the client right now so maybe I'll find something.

WildBamaBoy 19 Junior Poster

Yes.

WildBamaBoy 19 Junior Poster

I still need help with this. I've rewritten the server a little and getting the client to log in to it is almost complete. I still cannot communicate with the server using my computer's external IP address. I must use its address on my router (192.168.1.2) on my network of course to send messages to the server.

The client finally gave me this error.

Error: System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond ##.###.###.###:9852 (# is my external IP)

My server is listening on "all network interfaces", if I understand IPAddress.Any correctly, with the port I specified. (which is also forwarded on my router)

Here is part of my rewritten server's code. My client's code remains the same, except for sending the password I type instead of "Hello world".

public void Initialize(string s_Port, string Password)
        {
            try
            {
                Log("Initializing server...");

                Log("Getting External IP...");
                WebClient GetIPClient = new WebClient();
                UTF8Encoding UTF8 = new UTF8Encoding();

                string DownloadedIP = UTF8.GetString(GetIPClient.DownloadData("http://www.whatismyip.com/automation/n09230945.asp"));
                IPAddress ExternalIP = IPAddress.Parse(DownloadedIP);

                Log("Setting IP...");
                IPAddress IP = IPAddress.Any;

                Log("Checking port value...");
                int i_Port = Convert.ToInt32(s_Port);

                Log("Creating Listening Socket");
                TcpListener ListeningSocket = new TcpListener(IP, i_Port);

                ParameterizedThreadStart pts_ListeningThread = new ParameterizedThreadStart(
                                    delegate
                                    {
                                        WaitForLogin(ListeningSocket, Password);
                                    });

                Thread t_ListeningThread = new Thread(pts_ListeningThread);
                t_ListeningThread.Start();

                Log("Initialization complete. Waiting for client login.");

                Log("\r\n\t\t Client Connection Information:", false);
                Log("\t\t\t IP Address: " + ExternalIP, false);
                Log("\t\t\t Port: " …
WildBamaBoy 19 Junior Poster

Alright. I used IPAddress.Any and the client successfully sent a string to the server program with both running on my computer. However I had a chance to test it on a different network today and the client failed to send the string, yet neither program showed any error messages!

This is what my client does to send the string to the server.

private void ConnectButton_Click(object sender, EventArgs e)
        {
            try
            {
                TcpClient tcpclnt = new TcpClient();
                InfoBox.AppendText("Connecting...\r\n");

                tcpclnt.Connect("12.345.678.910", 9852); //External IP and port the server is listening on

                //Did not reach this point. But no errors.
                InfoBox.AppendText("Connected.\r\n");

                string str = "Hello world!";
                Stream stm = tcpclnt.GetStream();

                ASCIIEncoding asen = new ASCIIEncoding();
                byte[] ba = asen.GetBytes(str);
                InfoBox.AppendText("Sending.\r\n");

                stm.Write(ba, 0, ba.Length);

                byte[] bb = new byte[100];
                int k = stm.Read(bb, 0, 100);

                for (int i = 0; i < k; i++)
                    InfoBox.AppendText(Convert.ToChar(bb[i]).ToString());

                tcpclnt.Close();
            }

            catch (Exception E)
            {
                InfoBox.AppendText("Error: " + E.ToString());
            }

        }

And here is what my server does to listen for connections and data.

public void Start()
        {
            IP = IPAddress.Any;

            TcpListener Listener = new TcpListener(IP, Port);
            Listener.Start();

            List<char> chars = new List<char>();

            while (true)
            {
                try
                {
                    Socket S = Listener.AcceptSocket();

                    byte[] b = new byte[100];
                    int k = S.Receive(b);

                    for (int i = 0; i < k; i++)
                    {
                        chars.Add(Convert.ToChar(b[i]));
                    }

                    LogCT(string.Join("", chars)); //Update textbox with string sent by client
                    chars.Clear();

                    ASCIIEncoding ASCIIEnc = new ASCIIEncoding();
                    S.Send(ASCIIEnc.GetBytes("The string was recieved by the server.")); //Send response to client
                    LogCT("Sent answer.");
                }

                catch (Exception E)
                { …
WildBamaBoy 19 Junior Poster

I'm doing a client and server program and I am having issues getting my computer's local IP address. Dns.GetHostAddresses(Dns.GetHostName()); returns 2 addresses for me. My computer is behind a router with 2 others on the network. The code returns 192.168.1.2 (I know this is my computer), and 192.168.56.1 (I have no idea what this is.)

If that code returns more than one address, how can I test to see which one belongs to the computer the server is running on?

Also, I had originally tried to have my server listen for connections on my computer's external IP, but for some reason it kept complaining that the format wasn't correct. I couldn't figure out why, because it looked fine to me. So I did the above.

But if my client is running on another network, tries to send data to my computer's external IP (27.432.810.410; not real), and my server is listening on my computer's local IP (192.168.1.2), that's not going to work. Or will it??

WildBamaBoy 19 Junior Poster

I've stopped this project for now but I'll have a look at the Boost.Tokenizer whenever I start back. Thank you.

WildBamaBoy 19 Junior Poster

I'm at a point with this program that I need to do a lot of work with strings. This would be so much simpler to do in Python, however I don't want the entire program written in Python. How could I use functions from a Python script in C++?

WildBamaBoy 19 Junior Poster

Ah, my bad! Thank you.

WildBamaBoy 19 Junior Poster

This program gets a list of the processes running and displays them in a ListBox. When one is clicked it puts info about the process such as start time and filename in text boxes. But some of these don't return anything and the text box remains blank and I can't figure out why.

private void ProcessList_SelectedIndexChanged(object sender, EventArgs e)
{
     foreach (Process process in Process.GetProcesses())
     {
          if (process.ProcessName.ToString() == ProcessList.SelectedItem.ToString())
          {
               FilenameBox.Text = process.StartInfo.FileName; //Does not return
               UsernameBox.Text = process.StartInfo.UserName; //Does not return
               DirectoryBox.Text = process.StartInfo.WorkingDirectory; //Does not return
               StartTimeBox.Text = process.StartTime.ToString();
               RespondingBox.Text = process.Responding.ToString();
               CreatesWindowBox.Text = process.StartInfo.CreateNoWindow.ToString();
               VirtualMemoryBox.Text = process.VirtualMemorySize64.ToString();
          }
     }
}

Does anyone know why the top three do not return anything?

WildBamaBoy 19 Junior Poster

Thank you for the help. It runs correctly with all programs I have tested it with. Now I need to get a virus to really test it out. Not looking forward to that! :sweat:

WildBamaBoy 19 Junior Poster

Thank you for the quick reply. It works now that I break the while loop when CancellationPending is true, and now it barely uses the processor at all.

BTW. its not the best idea to be constantly looping and killing processes. You can put the system in a bad place, especially if the process you are killing has a babysitter or crash protection service attached to it.

I know, I crashed Windows with it not too long ago and had to start over. :$
This program is assuming the process its killing belongs to a virus and keep it from starting again so it can be deleted. Is it still a dangerous thing then? I doubt viruses would have some kind of crash protection.

Also I don't know what you mean by babysitter. Enlighten me!

WildBamaBoy 19 Junior Poster

This program will kill the process a user specifies and start a BackgroundWorker that constantly analyzes a list of running processes and kills it again if it starts. But it will not cancel even when I tell it to.

This is the BackgroundWorker's code.

private void KeepProcessKilled_DoWork(object sender, DoWorkEventArgs e)
        {
            while (true)
            {
                foreach (Process process in Process.GetProcesses())
                {
                    if (process.ProcessName == BadProcessName)
                    {
                        try
                        {
                            process.Kill();
                        }

                        catch
                        {
                        }
                    }
                }
            }
        }

And the code that stops it.

private void DeleteButton_Click(object sender, EventArgs e)
        {
            KeepProcessKilled.CancelAsync();
            ResultsBox.AppendText("KeepProcessKilled procedure has stopped.");
        }

The process continues to use 100 percent of the CPU and slows the system even after it is supposed to. I'm guessing I need to have a break somewhere in the while loop but I'm not sure where to put it or how to get to it when it's supposed to cancel.

Also is there a way to limit the CPU usage? 100 percent seems like a bit much for just checking what processes are running.

WildBamaBoy 19 Junior Poster

Yes, that works. But is there a way to make the AnswerBox available to other functions in the class without adding it as a parameter to all of the other functions?

WildBamaBoy 19 Junior Poster

That's not really how mine is set up and that doesn't seem to be working... I don't think I'm putting them in the right place. Here's what happens in mine. I probably don't have the best way of doing things. :P I'm a beginner to C#.

On the form. Pressing equals button

private void EqualsButton_Click(object sender, EventArgs e)
        {
            MathLogic.Start(EntryBox.Text.Replace(" ", "")); //Strip spaces and send to MathLogic
        }

Beginning of MathLogic class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ScientificCalculator
{
    public class MathLogic
    {
        public static string[] Operators = new string[] { "+", "–", "x", "÷" };
        public static string Entry = "";

        public static void Start(string e)
        {
            Entry = e;

            //Determine what to do to the entry. In this case 2 + 2
        }

Adding the numbers and updating the AnswerBox. This is what I want it to do

if (Operator == "+")
{
     try
     {
          int x = numbers[0];
          int y = numbers[1];

          AnswerBox.AppendText(Add(x, y).ToString());
     }

     catch
     {
          AnswerBox.AppendText("SYNTAX ERROR");
     }
}
WildBamaBoy 19 Junior Poster

I'm working on a scientific/algebraic calculator and I have put all of the code that will deal with any of the math in a separate class. However I cannot access any of the controls on the form from this class. I need to write the answer into the box on my form called AnswerBox. How do I allow this other class to use controls on the form?

WildBamaBoy 19 Junior Poster

You don't need to fill the spaces but if you want those unused variables, oh well.

You're still calling the function 'second' before you call 'first'.

WildBamaBoy 19 Junior Poster

Okay. It's pretty much solved. There are no longer any trails left when he moves around. There's still a few kinks here and there with moving around but I should be able to work those out. Thank you for your help.