0

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.

YFLu
  • 3
  • 1
  • 4
  • At least `if(setDate(2015,1,1);)` -> `if(setDate(2015,1,1))` to make it be compiled. – MikeCAT Dec 13 '15 at 07:59
  • 1
    Try checking the cause of failure via [`GetLastError` function](https://msdn.microsoft.com/ja-jp/library/windows/desktop/ms679360(v=vs.85).aspx). – MikeCAT Dec 13 '15 at 08:03
  • yea,I got an error:1314. A required privilege is not held by the client. – YFLu Dec 13 '15 at 08:07
  • 1
    According to [System Error Codes (1300-1699) (Windows)](https://msdn.microsoft.com/ja-jp/library/windows/desktop/ms681385(v=vs.85).aspx), it means `ERROR_PRIVILEGE_NOT_HELD`. Make sure you have required privilege. Try executing the program as an administrator. – MikeCAT Dec 13 '15 at 08:09
  • Got it. But how can I get the system administrator permissions in Qt?My system is Windows8.1. – YFLu Dec 13 '15 at 08:15
  • Possibly relevant: http://stackoverflow.com/questions/11199430/how-to-ask-for-administrator-privileges-in-windows-7 – Alan Stokes Dec 13 '15 at 09:00
  • Thanks, I am trying in this way. – YFLu Dec 13 '15 at 09:13

1 Answers1

3

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

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490