简体   繁体   English

100 毫秒计时器,我希望每个计时器滴答返回 0 或 1

[英]100 ms timer, i want every timer tick return 0 or 1

i want to make a function.我想做一个功能。

every timer ticks it will flash green color and every second timer ticks it will close green color.每个计时器滴答它都会闪烁绿色,每第二个计时器滴答它都会关闭绿色。

i have a timer in my win forms which is 100 ms interval.我的获胜形式中有一个计时器,间隔为 100 毫秒。

so every 200 ms my color will flash as green..所以每 200 毫秒我的颜色会闪烁为绿色..

can you help me about it你能帮我吗

this doesnt work这不起作用

var green = (((float)System.Environment.TickCount / 100) % 2) != 0;
if (green==true)
 {
greenColor);
if (green==false)
{                                 
noColor);
}

Because you have 2 states (color or no color) that swap each time I recommend to use a bool and just invert its value at the end of the timer-tick like so:因为每次我建议使用bool时都会交换 2 个状态(颜色或无颜色),并在计时器滴答结束时反转其值,如下所示:

bool tick;
private void theTimer_Tick( object sender, EventArgs e )
{
    if(tick)
    {
        colorLabel.BackColor = Color.Red;//Using label as example
    }
    else
    {
        colorLabel.BackColor = Color.Green;
    }
    tick = !tick;//Invert tick bool
}

This way you don't need the time of the counter and don't have to calculate all sorts of things.这样你就不需要计数器的时间,也不必计算各种事情。

You were almost there.你快到了。 Just don't use (float) .只是不要使用(float) Use integer arithmetic.使用整数算法。

bool green = (System.Environment.TickCount / 100) % 2 == 0;

If you use floating point remainder (which I don't recommend), then your test should not be == 0 it should be < 1 .如果您使用浮点余数(我不推荐),那么您的测试不应该是== 0而应该是< 1 Otherwise it'll only be green for 1 ms when the division remainder is precisely zero.否则,当除法余数恰好为零时,它只会显示绿色 1 毫秒。

bool green = (((float)System.Environment.TickCount / 100) % 2) < 1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM