C# - SendInput() from Windows Service not working but returns 1 - Win03

ぃ、小莉子 提交于 2019-12-13 02:34:33

问题


This is a somewhat unusual problem. I'm presently working on an effort to automate an Office application. Basically the issue is that my app is able to interact with the Office app correctly when I execute my app via RDP, but I am unable to send keystrokes using SendInput() if I set up the application to spawn from a windows service. OS is Win03 Std.

When spawning the app from a windows service I'm able to read window captions, automate through the interop, etc. as expected via pinvoke, but the SendInput() messages seemingly vanish even though the call returns a 1. All I'm trying to do at this point is send an escape keystroke to a dialog.

I've tried sending the keystrokes both as virtual keys and scancodes.

Any ideas or tips? Thanks in advance!

(BTW: I do realize that this sort of automation isn't supported/sanctioned by MSFT.)

EDIT: Just in case anyone else has this issue, this works:

[DllImport("user32")]

public static extern bool PostMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);


bool returnVal = NativeWin32.PostMessage(popup, 0x0100, new IntPtr(0x1b), IntPtr.Zero);

回答1:


I believe that SendInput will send keys to current active window (or window that has focus). Typically, windows services would be associated with different desktop (that interactive desktop) - so App launched from windows service would also be associated with the background desktop - so no active window (or window with focus) and that's may be the reason sendinout not working. You can perhaps try simulating key click by using SendMessage or PostMessage - you will need window handle for that.




回答2:


As of Windows Vista, services are no longer allowed to interact with the desktop. Which means they would not have a desktop context to send keyboard events to.



来源:https://stackoverflow.com/questions/4242909/c-sharp-sendinput-from-windows-service-not-working-but-returns-1-win03

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