Home > front end >  how do I pass a parameter to settimer?
how do I pass a parameter to settimer?

Time:03-10

I have a timer:

SetTimer(0, 0, 200, (TIMERPROC) & TimerProc);

As well as the ProcTimer function:

void TimerProc(int a)
{
    printf("Hello");
}

how do I pass parameter a to the timer?

CodePudding user response:

The short answer is that SetTimer simply doesn't support passing a parameter to the timer proc.

There are a couple of ways you can get around that if you really need to. One is to put the data in a global variable, and retrieve it from the global in the timer proc. If you might have more than one timer outstanding at a time, you can put the data into something like an std::map, with the timer ID as the key into the map (but this can get a little ugly if you need to pass different types of data to the different timer procs--still possible with something like std::variant, but ugly nonetheless).

But honestly, it's just easier and cleaner to simply avoid the problem entirely. SetTimer is mostly a hold-over from 16-bit Windows. If it works well for what you want, go ahead and use it--but in a case like this where it doesn't fit the need, use something else. In this case, the simplest way to handle the situation is probably to just spin up a thread:

int a = 1234;

t = std::thread([a] {
    std::this_thread::sleep_for(200ms); 
    printf("Received parameter: %d\n", a);
};

CodePudding user response:

create another global variable and assign a to this variable?

//like this
int b;

int f(int a) {
    b = a;
    //do something.
}

or you can directly put the SetTimer function into the TimerProc function.

//like this
void TimerProc(int a)
{
    SetTimer(0, 0, 200, (TIMERPROC) & TimerProc); //this function can use a as parameter.
    printf("Hello");
}
  •  Tags:  
  • c
  • Related