如何使一个按钮点击事件像3个案例的开关一样?

时间:2014-09-14 12:42:48

标签: c# .net winforms

按钮点击事件执行此方法:

public void Console(List<Keys> keys)
        {
            start = DateTime.Now;
            progressBar1.Maximum = 1;
            progressBar1.Step = 1;
            progressBar1.Value = 0;

            DoRequest(ScreenshotRequest.DannysCommands.NormalOperation);
            DoRequest(ScreenshotRequest.DannysCommands.Displayoverlays);
            DoRequest(ScreenshotRequest.DannysCommands.Dontdisplayoverlays);
        }

我希望第一次点击只能调用它:

DoRequest(ScreenshotRequest.DannysCommands.NormalOperation);

第二次点击只能调用:

DoRequest(ScreenshotRequest.DannysCommands.Displayoverlays);

第三次点击只能调用此行:

DoRequest(ScreenshotRequest.DannysCommands.Dontdisplayoverlays);

如果我第四次点击,它应该从第一次通话开始。订单总是:

DoRequest(ScreenshotRequest.DannysCommands.NormalOperation);
DoRequest(ScreenshotRequest.DannysCommands.Displayoverlays);
DoRequest(ScreenshotRequest.DannysCommands.Dontdisplayoverlays);

所以第四次点击应该调用这一行:

DoRequest(ScreenshotRequest.DannysCommands.NormalOperation); 

等等。

2 个答案:

答案 0 :(得分:0)

您可以使用计数器。在类中定义私有int全局变量。

private int count = 0 ;

像这样编辑你的方法:

    public void Console(List<Keys> keys)
    {
        if(count == 0)
        {
            // first condition
            count++;
        }
        else if(count == 1)
        {
            // second condition
            count++;
        }
        else
        {
            count = 0;
            // third condition
        }
    }

您也可以使用switch case语句而不是嵌套的if语句。

答案 1 :(得分:0)

只需创建类似“int command = 0”的字段,即0,1或2.

public void Console(List<Keys> keys)
        {
            start = DateTime.Now;
            progressBar1.Maximum = 1;
            progressBar1.Step = 1;
            progressBar1.Value = 0;

            if(command == 0)
                DoRequest(ScreenshotRequest.DannysCommands.NormalOperation);
            if(command == 1)
                DoRequest(ScreenshotRequest.DannysCommands.Displayoverlays);
            if(command == 2)
                DoRequest(ScreenshotRequest.DannysCommands.Dontdisplayoverlays);
            /* here can be switch instead of if */
            command++;
            command = command % 3;
        }