Home > Mobile >  How do I use SetTimer() and WM_TIMER with message boxes in c ?
How do I use SetTimer() and WM_TIMER with message boxes in c ?

Time:03-05

I am trying to make it so when a messagebox opens another one opens a couple seconds later without any user input (pressing the OK button). I want the old one to stay open, but a new one to appear. I know this uses the functions SetTimer() and WM_TIMER, but how do I do it? I have researched on how to do it and nothing seems to work.

#include <iostream>
#include <random>
#include <Windows.h>
#include <winternl.h>
#include "Uh_Oh.h"
#include <string>
#include "resource.h"
using namespace std;

void _MessageBox()
{
    HWND HWND1;
    MessageBox(HWND1, TEXT("Message"), TEXT("MsgBox"), MB_ICONWARNING | MB_OK);
    SetTimer(HWND1, 
        TIMER1,
        2000,
        (TIMERPROC)NULL);
    case WM_TIMER:

        switch (wParam)
        {
        case TIMER1:
            MessageBox(NULL, TEXT("Message 2"), TEXT("MsgBox 2"), MB_ICONWARNING | MB_OK);

            return 0;
        }
    }
}
int main()
{
    ShowWindow(::GetConsoleWindow(), SW_HIDE);
    _MessageBox();
}

CodePudding user response:

You are passing an uninitialized HWND to MessageBox().

Also, MessageBox() is a blocking function, it doesn't exit until the dialog is closed, so you need to create the timer before you call MessageBox() (unless you use SetWindowsHookEx() or SetWinEventHook() to hook the creation of the dialog).

Also, your syntax to handle the WM_TIMER message is just plain wrong.

MessageBox() displays a modal dialog and runs its own message loop, so you don't need to handle WM_TIMER manually at all. You can assign a callback to the timer, and let the modal loop dispatch the callback events for you.

Try something more like this:

#include <Windows.h>

void CALLBACK TimerProc(HWND, UINT, UINT_PTR, DWORD)
{
    MessageBox(NULL, TEXT("Message 2"), TEXT("MsgBox 2"), MB_ICONWARNING | MB_OK);
}

void _MessageBox()
{
    UINT timer = SetTimer(NULL, 0, 2000, TimerProc);
    if (timer) {
        MessageBox(NULL, TEXT("Message"), TEXT("MsgBox"), MB_ICONWARNING | MB_OK);
        KillTimer(NULL, timer);
    }
}

int main()
{
    ShowWindow(GetConsoleWindow(), SW_HIDE);
    _MessageBox();
} 
  • Related