使用复选框和间隔在 C# 中循环

Loop in C# with a checkBox and intervals

我希望当我选中 checkBox1 时重复此代码,直到取消选中 checkBox1:

                MemLib.WriteMemory("base+02DB12E8", "float", "500");
                MemLib.WriteMemory("base+025EBA28", "int", "1");
                Thread.Sleep(1000);
                MemLib.WriteMemory("base+025EBA28", "int", "0");
                Thread.Sleep(1000);

下面是取消选中 checkBox1 时要执行的代码:

                MemLib.WriteMemory("base+02DB12E8", "float", "500");
                MemLib.WriteMemory("base+025EBA28", "int", "0");

这就是我所做的:

    private void checkBox1_CheckedChanged(object sender, EventArgs e)
    {
        while (true)
        {
            if (checkBox1.Checked)
            {
                MemLib.WriteMemory("base+02DB12E8", "float", "500");
                MemLib.WriteMemory("base+025EBA28", "int", "1");
                Thread.Sleep(1000);
                MemLib.WriteMemory("base+025EBA28", "int", "0");
                Thread.Sleep(1000);
            }
            else
            {
                MemLib.WriteMemory("base+02DB12E8", "float", "500");
                MemLib.WriteMemory("base+025EBA28", "int", "0");
            }
        }
    }

有人有解决办法吗?

您可以使用计时器。像这样:

private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
    if (checkBox1.Checked)
    {
        Timer1.Interval = 1000;
        Timer1.Enabled = true;
    }
}

private void Timer1_Tick(object Sender, EventArgs e)
{
    if (checkBox1.Checked)
    {
        MemLib.WriteMemory("base+02DB12E8", "float", "500");
        MemLib.WriteMemory("base+025EBA28", "int", "1");
        Thread.Sleep(1000);
        MemLib.WriteMemory("base+025EBA28", "int", "0");
        Thread.Sleep(1000);
    }
    else
    {
        MemLib.WriteMemory("base+02DB12E8", "float", "500");
        MemLib.WriteMemory("base+025EBA28", "int", "0");
    }
}

https://docs.microsoft.com/en-us/dotnet/desktop/winforms/controls/run-procedures-at-set-intervals-with-wf-timer-component?view=netframeworkdesktop-4.8