Windows service with gui

Windows Service with GUI monitor?

I have a C++ Win32 application that was written as a Windows GUI project, and now I’m trying to figure out to make it into a Service / GUI hybrid. I understand that a Windows Service cannot / should not have a user interface. But allow me to explain what I have so far and what I’m shooting for.

WHAT I HAVE NOW is a windows application. When it is run it places an icon in the system tray that you can double-click on to open up the GUI. The purpose of this application is to process files located in a specified directory on a nightly schedule. The GUI consists of the following:

  • A button to start an unscheduled scan/process manually.
  • A button to open a dialog for modifying settings.
  • A List Box for displaying status messages sent from the processing thread.
  • A custom drawn window for displaying image data (the file processing includes the creation and saving of images).
  • A status bar — while a process is not running, it shows a countdown to the next scheduled scan. During a scan it also provides some status feedback, including a progress bar.

WHAT I’M SHOOTING FOR is a service that will run on boot-up and not require a user to login. This would consist of the scheduled file processing. However, when a user logs in I would still like the tray icon to be loaded and allow them to open up a GUI as I described above to monitor the current state of the service, change settings, start a scan manually, and monitor the progress of a scan.

I’m sure that I have seen applications like this — that function as a service even when I’m not logged in, but still give me a user interface to work with once I do log in.

I’m thinking that instead of having a single multi-threaded application that sends messages to the GUI thread from the processing thread, I need two applications — a Service to perform the processing and a GUI application to provide visual feedback from the Service and also send messages to the Service (for example, to start a scan manually). But I am new to Windows Services and have no idea how this is done.

It is also possible that I’m completely off base and a Service is not what I’m looking for at all.

Any help / ideas / suggestions would be greatly appreciated! Thank you.

Устанавливаем GUI на Windows Server Core

В прошлом нашем посте мы рассказали как готовим стандартные клиентские виртуальные машины и показали на примере нашего нового тарифа с Ultralight windows vds за 99 рублей, как мы создавали стандартный образ Windows Server 2019 Core.

В службу поддержки стали поступать заявки как работать с Server 2019 Core без привычной графической оболочки. Мы решили показать работу с Windows Server 2019 Core и как установить на него GUI.

Не повторяйте это на рабочих машинах, не используйте Server Core как рабочий стол, отключите RDP, обезопасьте свою информационную систему, именно безопасность — это главная фишка «Core» инсталляции.

Читайте также:  Linux с интерфейсом как windows

В одной из следующих наших статей мы рассмотрим таблицу совместимости программ с Windows Server Core. В этой статье мы затронем то, как установить оболочку.

Оболочка сторонними средствами

1. Сложный, но наиболее экономичный способ

В Server Core из коробки нет привычного нам explorer.exe, чтобы облегчить нам жизнь, мы скачаем explorer++. Он заменяет все, что умеет оригинальный explorer. Рассматривался только explorer++, но подойдет почти любой файловый менеджер, в том числе Total Commander, FAR Manager и другие.

Сначала нам нужно скачать файл на сервер. Это можно сделать через SMB (общую папку), Windows Admin Center и Invoke-WebRequest, он работает с параметром -UseBasicParsing.

Где -uri это URL файла, а -OutFile полный путь куда его скачивать, указывая расширение файла и

C помощью Powershell:

На сервере создаём новую папку:

Расшариваем общую папку:

На вашем ПК папка подключается как сетевой диск.

Через Windows Admin Center создаем новую папку выбрав пункт в меню.

Переходим в общую папку и жмем кнопку отправить, выбираем файл.

Добавляем оболочку в планировщик.

Если вы не хотите запускать оболочку вручную при каждом входе в систему, то нужно добавить её в планировщик задач.

Без планировщика можно запустить через CMD:

Способ 2. Запускаем родной Explorer


Remember, no GUI

Server Core App Compatibility Feature on Demand (FOD), вернет в систему: MMC, Eventvwr, PerfMon, Resmon, Explorer.exe и даже Powershell ISE. Подробнее можете ознакомиться на MSDN. Существующий набор ролей и компонентов он не расширяет.

Запустите Powershell и введите следующую команду:

Затем перезагрузите сервер:

После этого вы сможете запускать даже Microsoft Office, но потеряете примерно 200 мегабайт ОЗУ навсегда, даже если в системе нет активных пользователей.


Windows Server 2019 c установленным Features on Demand


Windows Server 2019 CORE

На этом всё. В следующей статье мы рассмотрим таблицу совместимости программ с Windows Server Core.

Предлагаем обновлённый тариф UltraLite Windows VDS за 99 рублей с установленной Windows Server 2019 Core.

Windows service with gui

A little library forked from windowsservicehelper for adding an (optional) gui in debug mode to windows services. It allows you to «just press F5» and run the windows service already.

Helps by creating a Play/Stop/Pause UI (or just running the service) when running with a debugger attached, but also allows the windows service to be installed and run by the Windows Services environment as well. All this with one line of code!

Helps by creating a Play/Stop/Pause UI (or just running the service) when running with a debugger attached, but also allows the windows service to be installed and run by the Windows Services environment as well. All this with one line of code!

What is Service Helper?

Being someone who writes Windows Services a lot, it can be frustrating to deal with the headaches involved in debugging services. Often it involves tricks, hacks, and partial workarounds to test all of your code. There is no «just hit F5» experience for Windows Services developers.

Service Helper solves this by triggering a UI to be shown if a debugger is attached that simulates (as closely as possible) the Windows Services Environment.

Just hit F5, and this UI automatically appears. If there is no debugger attached, your service will execute as normal and can be installed in the Windows Services system.

Читайте также:  Что лучше linux или windows почему

The easiest way to get Windows Service Helper in your project is to use the NuGet package ServiceProcess.Helpers on the NuGet official feed.

Simply make a few changes to the typical code in the «Program.cs» for your application:

To install simply add the following nuget package:

Config Options — You can control all the behaviours — including turning off the UI and just running it already:

  • More closely simulating the Windows Services environment and allowing calls like «RequestAdditionalTime» and enforcing timeouts.

Improve the code

This code is not perfection. If you have a bugfix or enhancement you’d like to see in Windows Service Helper, please send me a pull request and I will put your name in lights (er. maybe here on this wiki page at least).

About

A little library forked from windowsservicehelper for adding a gui in debug mode to windows services

How can a Windows service execute a GUI application?

I have written a Windows service that allows me to remotely run and stop applications. These applications are run using CreateProcess, and this works for me because most of them only perform backend processing. Recently, I need to run applications that present GUI to the current log in user. How do I code in C++ to allow my service to locate the currently active desktop and run the GUI on it?

9 Answers 9

Roger Lipscombe’s answer, to use WTSEnumerateSessions to find the right desktop, then CreateProcessAsUser to start the application on that desktop (you pass it the handle of the desktop as part of the STARTUPINFO structure) is correct.

However, I would strongly recommend against doing this. In some environments, such as Terminal Server hosts with many active users, determining which desktop is the ‘active’ one isn’t easy, and may not even be possible.

But most importantly, if an application will suddenly appear on a user’s desktop, this may very well occur at a bad time (either because the user simply isn’t expecting it, or because you’re trying to launch the app when the session isn’t quite initialized yet, in the process of shutting down, or whatever).

A more conventional approach would be to put a shortcut to a small client app for your service in the global startup group. This app will then launch along with every user session, and can be used start other apps (if so desired) without any juggling of user credentials, sessions and/or desktops.

Also, this shortcut can be moved/disabled by administrators as desired, which will make deployment of your application much easier, since it doesn’t deviate from the standards used by other Windows apps.

The short answer is «You don’t», as opening a GUI program running under another user context is a security vulnerability commonly known as a Shatter Attack.

Take a look at this MSDN article: Interactive Services. It gives some options for a service to interact with a user.

In short you have these options:

Display a dialog box in the user’s session using the WTSSendMessage function.

Create a separate hidden GUI application and use the CreateProcessAsUser function to run the application within the context of the interactive user. Design the GUI application to communicate with the service through some method of interprocess communication (IPC), for example, named pipes. The service communicates with the GUI application to tell it when to display the GUI. The application communicates the results of the user interaction back to the service so that the service can take the appropriate action. Note that IPC can expose your service interfaces over the network unless you use an appropriate access control list (ACL).

Читайте также:  Поставит windows с usb

If this service runs on a multiuser system, add the application to the following key so that it is run in each session: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run. If the application uses named pipes for IPC, the server can distinguish between multiple user processes by giving each pipe a unique name based on the session ID.

Windows service with gui

A little library forked from windowsservicehelper for adding an (optional) gui in debug mode to windows services. It allows you to «just press F5» and run the windows service already.

Helps by creating a Play/Stop/Pause UI (or just running the service) when running with a debugger attached, but also allows the windows service to be installed and run by the Windows Services environment as well. All this with one line of code!

Helps by creating a Play/Stop/Pause UI (or just running the service) when running with a debugger attached, but also allows the windows service to be installed and run by the Windows Services environment as well. All this with one line of code!

What is Service Helper?

Being someone who writes Windows Services a lot, it can be frustrating to deal with the headaches involved in debugging services. Often it involves tricks, hacks, and partial workarounds to test all of your code. There is no «just hit F5» experience for Windows Services developers.

Service Helper solves this by triggering a UI to be shown if a debugger is attached that simulates (as closely as possible) the Windows Services Environment.

Just hit F5, and this UI automatically appears. If there is no debugger attached, your service will execute as normal and can be installed in the Windows Services system.

The easiest way to get Windows Service Helper in your project is to use the NuGet package ServiceProcess.Helpers on the NuGet official feed.

Simply make a few changes to the typical code in the «Program.cs» for your application:

To install simply add the following nuget package:

Config Options — You can control all the behaviours — including turning off the UI and just running it already:

  • More closely simulating the Windows Services environment and allowing calls like «RequestAdditionalTime» and enforcing timeouts.

Improve the code

This code is not perfection. If you have a bugfix or enhancement you’d like to see in Windows Service Helper, please send me a pull request and I will put your name in lights (er. maybe here on this wiki page at least).

About

A little library forked from windowsservicehelper for adding a gui in debug mode to windows services

Оцените статью