C++ SendInput possible in Windows Service?

只愿长相守 提交于 2019-12-11 01:05:09

问题


First off, I'd like to say that I've used StackOverflow for years, and this is the first time I haven't found an existing answer. A testament to what a valuable resource this is.

Background: I'm trying to catch MIDI input from a connected device and have it trigger keyboard events to whichever window has focus. I was able to do this successfully using SendInput in a Windows Console application, but would prefer to run this as a service. I was able to hide the console window and have it work, which is a passable solution, but I would prefer to get it working without seeing the console for a second before it hides.

The problem: After doing some research on making a Windows Service, primarily using the following sources:

MSDN Windows Service Tutorial

CodeProject Windows Service Tutorial

I got the impression that there might be security restrictions that prevent SendInput from working in a Windows Service (and understandably so). I decided to try a proof of concept first before getting too far to see if I could get it to work. I ran the sample code from MSDN and was able to get it to install and work as described in the tutorial. After doing so, I added the following code to their example in the class SampleService.cpp:

    while (!m_fStopping)
{
    // Perform main service function here...
    INPUT keyEvents;
    keyEvents.type = INPUT_KEYBOARD;
    keyEvents.ki.wScan = 0;
    keyEvents.ki.time = 0;
    keyEvents.ki.dwExtraInfo = 0;

    keyEvents.ki.wVk = 0x41;
    keyEvents.ki.dwFlags = 0;
    SendInput(1, &keyEvents, sizeof(INPUT));
    ::Sleep(5000);  // Simulate some lengthy operations.
}

I did not change any other code. After I installed the service, I found it listed in Services, and before starting it, I went into Properties, to the Logon tab, and set Logon to Local System Account and checked Allow Service to Interact with Desktop. When running the service I don't see the lower case a I expect in any window that accepts text.

Is it possible to use SendInput in a service? If so, how? If not, is there another way to have a service send key events to any active window?

I'm using Windows 8 64bit, IDE is VS2012 Professional.


回答1:


Its not possible to conduct any interaction with the user from Windows Services. Services run isolated for security reasons. They run in a separate session, session 0. So what you are trying to do, won’t work and for a reason.



来源:https://stackoverflow.com/questions/32474969/c-sendinput-possible-in-windows-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!