Run a function every second Visual C #

I have a problem with the timer. I have a function in a function (draw in func)

void func(){

 /*...do something ... */
for(){
   for() {
  /*loop*/

 draw(A,B, Pen);

 }

/*... do something ...*/
  }
}

This is a drawing function.

   public void draw1(Point Poc, Point Kra, Pen o) {
      Graphics g = this.CreateGraphics();
      g.DrawLine(o,Poc.X+4, Poc.Y+4,Kra.X+4, Kra.Y+4);
      g.Dispose();
      }

I call the function "func" when the button is pressed

private void button4_Click(object sender, EventArgs e){

    func();

}

I want to call the evry second draw function (draw a line every second). Between the drawings, the function should continue to work and calculate = cycle, and then draw the next line for some time (interval). I tried using

timer1.Tick += new EventHandler(timer1_Tick);

etc..

private void timer1_Tick(object sender, EventArgs e)
    {
        ...
        draw(A, B, Pen)
    }

etc..

but all this stops my function and draws one random line. I just need time (interval) between two drawings in the "func" function. Without a timer, it works fine, but immediately all the lines, I need a slow drawing. Greetings.

0
source share
4 answers

SOLVED currently with

System.Threading.Thread.Sleep(700);
-9

, , , , Timer , . :

Timer myTimer = new Timer();
myTimer.Elapsed += new ElapsedEventHandler(DisplayTimeEvent);
myTimer.Interval = 1000; // 1000 ms is one second
myTimer.Start();

public static void DisplayTimeEvent(object source, ElapsedEventArgs e)
{
    // code here will run every second
}
+12

try it

var aTimer = new System.Timers.Timer(1000);

aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);

aTimer.Interval = 1000;
aTimer.Enabled = true;       

//if your code is not registers timer globally then uncomment following code

//GC.KeepAlive(aTimer);



private void OnTimedEvent(object source, ElapsedEventArgs e)
{
    draw(A, B, Pen);
}
+2
source

You do not draw in the WinForms application, you are responding to updates or emails. Do what you want to do in the Paintevent form (or override the method OnPaint). When you want the shape to be redrawn, use Form.Invalidate. For example, call Form.Invalidatethe timer timer ...

+1
source

All Articles