Simple c++ program fails to run as a scheduled-tas

2019-08-11 20:35发布

问题:

I'm running Win 7 x64 and I've written a very simple c++ program with Microsoft Visual c++ 2010 express, to be run as a task in task scheduler. this is the programs code (there's no resource files or header files):

#include <windows.h>

int WINAPI WinMain(HINSTANCE inst,HINSTANCE prev,LPSTR cmd,int show)
{
      // Simulate numlock key press
         keybd_event( VK_NUMLOCK,
                      0x45,
                      KEYEVENTF_EXTENDEDKEY | 0,
                      0 );

      // Simulate numlock key release
         keybd_event( VK_NUMLOCK,
                      0x45,
                      KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP,
                      0);
      return 0;
}

I would like the task to be run as SYSTEM account to not rely on any users credentials or whether they are logged in or not. However, I am unable to make it successfully run as a task in task scheduler. after doing some research, i now suspect that the fact that tasks running as SYSTEM, can not be interactive, is the cause of this program not working correctly ( by using PsExec tool, i can confirm that 'PsExec -s -i my_program.exe' works, while 'PsExec -s my_program.exe' fails to change the numlock state.).

From what i can see, the program doesn't appear to be interactive at all. Can anyone please help me to figure out why is this happening and how it can be fixed? Thanks in advance

回答1:

If i may answer my own question, This, appears to be some sort of security measure by windows to avoid receiving keyboard/mouse events from outside of users desktop (See here).