简体   繁体   English

如何使我的控制台C ++程序在后台运行?

[英]How do I make my console C++ program work in the background?

I need it to take up as little processor time as possible and there's absolutely no need to create an actual window. 我需要它占用尽可能少的处理器时间,并且绝对不需要创建实际的窗口。 I just need that process to hang out in the backdground. 我只需要该过程可以在后台进行。

This request fits Windows Service concept best. 此请求最适合Windows Service概念。 The example . 这个例子 You may implement that many different ways, C/C++ with Qt or not/C#. 您可以实现许多不同的方式,使用Qt或不使用Ct的C / C ++。 The advantage of creating the service and not hidden console is that the program is manageable via standard Windows Service interface for (un)register/start/stop/etc. 创建服务而不是隐藏控制台的优点是,该程序可通过用于(取消)注册/启动/停止/等的标准Windows服务界面进行管理。 with both administrative UI and console utilities. 同时具有管理UI和控制台实用程序。

Making the app consuming less CPU is much more delicate thing and depends on what your app does but the simpler answer is that don't run tight loops and make it wait until it is needed to process something. 使应用程序消耗更少的CPU更为复杂,这取决于您的应用程序执行的操作,但更简单的答案是:不要运行紧密的循环,并使其等待直到需要处理某些东西为止。 There are too many things to cover eg threading etc. but we don't know what your program does. 有太多东西要介绍,例如线程等。但是我们不知道您的程序做什么。

Windows application are running always at background, and not have to be with GUI window, so this is what you ask for. Windows应用程序始终在后台运行,而不必在GUI窗口中运行,因此这就是您所需要的。 If you already have a console application, you'll just need to do the following: 如果已经有了控制台应用程序,则只需执行以下操作:

  • In visual studio create an empty project (not a console, a Win32 app). 在Visual Studio中创建一个空项目(而不是控制台,Win32应用程序)。
  • Add new c++ source file into that project 将新的C ++源文件添加到该项目
  • put the following code in the new source file: 将以下代码放入新的源文件中:

this: 这个:

#include <Windows.h>

int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR pCmdLine, int nCmdShow)
{
    //your program should replace this loop:
    while(1){
       Sleep(100); //because of the the empty loop, I don't want to waste CPU...
    }
    return 0;
}
  • use this wWinMain as your main , if you need arguments you'll need to parse pCmdLine. 使用此wWinMain作为main ,如果需要参数,则需要解析pCmdLine。
  • Note that this is the UNICODE version, for non UNICODE use just WinMain and PSTR pCmdLine 请注意,这是UNICODE版本,对于非UNICODE,仅使用WinMainPSTR pCmdLine

like this: 像这样:

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pCmdLine, int nCmdShow)
  • if your program needed to be stopped you can use task manager to kill it. 如果需要停止程序,则可以使用任务管理器将其杀死。
  • a system try icon also can help you, but then you'll need at least one window (possibly hidden) 系统尝试图标也可以为您提供帮助,但是您至少需要一个窗口(可能已隐藏)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM