YFLu
YFLu

Reputation: 3

How to change windows system time in Qt?

I want to change my system time ,How can I change the Windows system time in Qt? I used this way,but failed!

#include <QApplication>
#include <iostream>
#include <time.h>
#include <windows.h>
#include <QDateTime>
#include <QDebug>
using namespace std;
bool setDate(int,int,int);      
int main(int argc, char *argv[])
{
   QApplication a(argc, argv);
   MainWindow w;
   w.show();
   qDebug()<<QDateTime::currentDateTime()<<endl;    //before change time                        
   if(setDate(2015,1,1))                           //set time
   {
     qDebug()<<QDateTime::currentDateTime()<<endl;  //if succeed,output time
   }  
   return a.exec();
}
bool setDate(int year,int mon,int day)
{
   SYSTEMTIME st;
   GetSystemTime(&st);    // Win32 API get time
   st.wYear=year;         //set year
   st.wMonth=mon;         //set month
   st.wDay=day;           //set day

  return SetSystemTime(&st);    //Win32 API set time
 }

Thank you in advance.

Upvotes: 0

Views: 3496

Answers (1)

David Heffernan
David Heffernan

Reputation: 613053

Changing the system time requires admin rights. That means you need to:

  • Add the requireAdministrator option to your manifest so that the program always has admin rights. That's a bad idea and you won't enjoy the UAC dialog every time you start.
  • Or, change the time by starting a separate process that runs as administrator. Another executable with the appropriate manifest, a process started with the runas shell verb, or one started with the COM elevation moniker.

If this is gobbledygook to you, you need to read up on UAC. Start here: https://msdn.microsoft.com/en-us/library/windows/desktop/dn742497(v=vs.85).aspx

Upvotes: 3

Related Questions