winapitime

How to call a kernel32.dll function GetTickCount() using LoadLibrary(..) in C++


I am searching for a function to get time in milliseconds on a windows machine. Essentially, I want to call this WinAPI function GetTickCount(), but I'm stuck on "use LoadLibrary(...) n call GetTickCount() function" part..

I searched every forum n googled it but everywhere people have used incomplete codes that don't compile..Can anyone write a short sample program to load kernel32.dll and call GetTickCount() to display the time in milliseconds?

Please write code that compiles!


Solution

  • You can't load kernel32.dll, it's already loaded into every process. And GetTickCount exists on every version of Windows, so you don't need GetProcAddress to see if it exists. All you need is:

    #include <windows.h>
    #include <iostream>
    
    int main(void)
    {
        std::cout << GetTickCount() << std::endl;
    }
    

    A dynamic load example (since winmm.dll is not preloaded):

    #include <windows.h>
    #include <iostream>
    
    int main(void)
    {
        HMODULE winmmDLL = LoadLibraryA("winmm.dll");
    
        if (!winmmDLL) {
            std::cerr << "LoadLibrary failed." << std::endl;
            return 1;
        }
    
        typedef DWORD (WINAPI *timeGetTime_fn)(void);
        timeGetTime_fn pfnTimeGetTime = (timeGetTime_fn)GetProcAddress(winmmDLL, "timeGetTime");
    
        if (!pfnTimeGetTime) {
            std::cerr << "GetProcAddress failed." << std::endl;
            return 2;
        }
    
        std::cout << (*pfnTimeGetTime)() << std::endl;
        return 0;
    }
    

    I've successfully compiled and run this example using Visual Studio 2010 command prompt, no special compiler or linker options are needed.