按钮单击其他方法

按钮单击其他方法

本文介绍了按钮单击其他方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨我有一个场景,任何人都可以解决这个问题..

我在课堂上点击了一个按钮并且工作正常OK.but我想知道是否再次点击该按钮当一个事件被触发时。如果我发现该按钮被点击,那么我必须停止它的动作。

Hi I have a scenario here can anyone sort out this..
I performed a button click in a class and its working fine OK.but I want to find that whether that button is clicked again when an event is fired. If i find that button is clicked then i have to stop its action.

推荐答案

private void MyButton_Click(object sender, EventArgs e)
    {
    for (int i = 0; i < 10000000; i++)
        {
        DoIt();
        }
    }

然后在长操作完成之前不会发生任何其他事情 - 因为线程忙于执行长操作。

为了让按钮完全工作以停止操作,您必须将操作移动到新线程。这并不难,但确实需要一点工作。最简单的方法是使用BackgroundWorker:

Then nothing else will happen until the long operation is completed - because the thread is busy doing the long operation.
In order to get the button to work at all in order to stop the operation, you have to move the operation to a new thread. That's not difficult, but it does need a little work. The easiest way to do it is to use a BackgroundWorker:

private BackgroundWorker worker = null;
private void MyButton_Click(object sender, EventArgs e)
    {
    worker = new BackgroundWorker();
    worker.DoWork += worker_DoWork;
    worker.RunWorkerCompleted += worker_RunWorkerCompleted;
    worker.WorkerSupportsCancellation = true;
    worker.RunWorkerAsync();
    }

void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
    }

void worker_DoWork(object sender, DoWorkEventArgs e)
    {
    for (int i = 0; i < 10000000; i++)
        {
        DoIt();
        }
    }

然后您可以使用它来取消长时间操作:

Then you can use that to cancel the long operation:

private BackgroundWorker worker = null;
private void MyButton_Click(object sender, EventArgs e)
    {
    if (worker == null)
        {
        worker = new BackgroundWorker();
        worker.DoWork += worker_DoWork;
        worker.RunWorkerCompleted += worker_RunWorkerCompleted;
        worker.WorkerSupportsCancellation = true;
        worker.RunWorkerAsync();
        }
    else
        {
        worker.CancelAsync();
        }
    }

void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
    worker = null;
    }

void worker_DoWork(object sender, DoWorkEventArgs e)
    {
    BackgroundWorker worker = sender as BackgroundWorker;
    if (worker != null)
        {
        for (int i = 0; i < 10000000 && !worker.CancellationPending; i++)
            {
            DoIt();
            }
        }
    }



这篇关于按钮单击其他方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 05:06