JITIN MALHOTRA
JITIN MALHOTRA

Reputation: 55

how to check whether a button is clicked, inside another button click event in windows form application in C#

well i am having two buttons on a form and I want to start data transfer with the first button and stop on the press of a second button.

code is:

private void stdaq_Click(object sender, EventArgs e)
{
    stopped = false;

    //while (stopped == false)

    if (sender == spdaq)
    {
        stopped = true;
        ///break;
        Process();
    }
    else if (sender == stdaq)
    {
        Process();
    }
}

here stdaq is the start button and spdaq is the stop button, the process function is a function which i am implementing and in that with the stopped variable of bool type i am implementing two different functions inside process method, but i want to continually check whether the stop button is pressed or not but here with this code i got no success.

so please help me with how to pass the value true to the stopped variable inside the event click function of start button itself on the press of stop button.

Upvotes: 2

Views: 1255

Answers (2)

Fabjan
Fabjan

Reputation: 13676

Create cancellation token, start asynchronous Task in button start event handler put your method in this Task, pass reference to this cancellation token and use it to stop this task in Stop button event handler when you'll need it later.

More information : https://msdn.microsoft.com/en-us/library/jj155759.aspx

Example of how you can use it:

    static CancellationTokenSource cts;
    static Task t;

    private void Method()
    {
        while (!cts.IsCancellationRequested) 
        {
             // your logic here
        }
        t = null;
    }

    private void stdaq_click (object sender, EventArgs e)
    {           
       if(t != null) return;
       cts = new CancellationTokenSource();
       t = new Task(Method, cts.Token, TaskCreationOptions.None);
       t.Start();
    }

    private void spdaq_Click(object sender, EventArgs e) 
    {
       if(t != null) cts.Cancel(); 
    }

Upvotes: 1

DrKoch
DrKoch

Reputation: 9782

Use two separate Handlers for the start and the stop button. This makes your logic much simpler to follow. Then do soemthing like this:

private void stdaq_Click(object sender, EventArgs e) // Start
{
    Process(true);
}

private void spdaq_Click(object sender, EventArgs e) // Stop
{
    Process(false);
}

Or even better: Create two seperate Methods StartProcess() and StopProcess().

Upvotes: 1

Related Questions