hi, am currently working on a assignment in which i hace to make a graphic using the g class blink on and off for certain intervals. i was wondering if someone would know how to make a graphic do so since i only know how to make a picture blink

Recommended Answers

All 2 Replies

Here's an example:

Add a class-level bool variable, i.e declare it above "public Form1() { ....":

[B]bool blink = false;[/B]

public Form1()
{
    InitializeComponent();
}

Add a timer and 2 buttons to your form. Name the first button "Start" and other "Stop". Add click event for both buttons and use this code:

// Start Button
private void StartBtn_Click(object sender, EventArgs e)
{
    timer1.Start();
}

// Stop Button
private void StopBtn_Click(object sender, EventArgs e)
{
    timer1.Stop();
    // Clear
    this.Invalidate();
}

Add a Paint event to the form and use this code:

private void Form1_Paint(object sender, PaintEventArgs e)
{
   // Make sure timer is started
   if (timer1.Enabled)
   {
      if (!blink)
      {
        e.Graphics.FillRectangle(Brushes.Red, new Rectangle(10, 10, 100, 100));
        blink = true;
      }
      else if (blink)
      {
        blink = false;
      }
   }
}

Finally, double-click the Timer to add Tick event and use this code:

private void timer1_Tick(object sender, EventArgs e)
{
   // Fire "Paint" event
   this.Invalidate();
}

It works like this: By default, the blink variable is set to false. When the paint event is fired a red rectangle is drawn and blink is set to true. When its fired again since blink is set to true, it clears the rectangle and sets blink back to false and it goes go on like this.

Thanks

farooqaaa, That is a great code snippet you posted for the OP. But I do have one thing to suggest. I would use the Timer tick event to change the state of the variable. Not the paint event, as many thing can cause the paint event to be fired. if one is to expect that the blinking should be consistent. Then the toggle should also be done on interval, The paint event should only be used to paint, not change variables.

The code above would cause parts of the blinking graphic to act erratically if other windows were dragged around above the current one.

Although you did a great job of explaining your reasoning, and of course the code would certainly work either way.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.