且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在登录 Windows 之前启动 WPF 应用程序?

更新时间:2023-12-04 09:51:52

不,这是不可能的.WPF 应用程序是用户模式应用程序,因此它们必须在登录用户的上下文中运行.由于 Windows 是一个多用户操作系统,因此操作系统可能正在运行,但没有用户登录.在这种情况下,您的应用程序将无处可运行.

No, this is not possible. WPF applications are user-mode applications, so they must be run within the context of a logged-in user. Since Windows is a multi-user operating system, it is possible for the OS to be running, but no users to be logged in. In those situations, there is no place for your application to run.

Windows 服务是唯一可以做到这一点的,这正是因为它们不在特定的用户上下文中运行.事实上,对于想要创建与用户交互的 Windows 服务的开发人员来说,这个相同的功能常常是令人沮丧的根源.这是不可能的(至少从 Windows Vista 开始不是这样,修补了之前版本中存在的所有安全漏洞).

Windows services are the only thing that can do this, and that's precisely because they do not run under a particular user context. In fact, this same feature is often a source of frustration for developers who want to create a Windows service that interacts with the user. That's not possible (at least not as of Windows Vista, which patched all the security holes present in prior versions).

替代解决方案:

  • 将您的应用程序添加到默认用户的启动"中文件夹,这将强制它在用户每次登录计算机时启动.

  • Add your application to the default user's "Startup" folder, which will force it to launch each time that a user logs in to the machine.

在这种情况下,它唯一运行的时间是没有用户登录时,在这种情况下,很难想象您的应用/服务实际上对任何人都有好处.

In this scenario, the only time it will not be running is when no users are logged in, in which case it's sort of hard to imagine that your app/service is actually doing anyone any good.

将每台计算机配置为在 Windows 启动时自动以特定用户身份登录.结合上述内容,您可以解决这样一个事实:即使在崩溃/重新启动后,计算机也可能会在没有用户登录的情况下离开.

Configure each machine to automatically log in as a particular user whenever Windows starts up. Combining this with the above, you work around the fact that the computer could ever be left without a user logged in, even immediately after a crash/restart.

尽管拥有一个独立的用户模式应用程序(WPF、WinForms 或其他)可以显示 UI 控件的模式,但在后台运行的 Windows 服务是一种很常见的模式.我不确定您认为该设置有什么问题.在需要信息时轮询服务并没有错.根据定义,服务不需要用户干预.将需要用户干预的部分分离到单独的应用程序中不仅是典型的做法,而且是必要的.

Although the pattern of having a separate user-mode application (WPF, WinForms, or whatever) that can show a UI control the Windows service running in the background is quite a common one. I'm not sure what you think is wrong with that setup. There's nothing wrong with polling the service when necessary for information. Services by definition do not require user intervention. Separating the part that requires user intervention out into a separate app is not only the typical practice, but necessary.