C++启动程序而不打开控制台

C++ launching program without console opening

本文关键字:控制台 启动 程序 C++      更新时间:2023-10-16

我一直在开发一个应用程序,以设置我在这里找到的另一个应用程序的桌面背景基础:http://www.optimumx.com/downloads.html#SetWallpaper。这个想法是每 10 分钟将背景设置为一张墙纸,因此它会使用命令"SetWallpaper.exe/D:S Wallpaper.jpg"启动 SetWallpaper.exe,但是当我启动我的应用程序时,它会创建一个不会自动关闭的控制台窗口,当我手动关闭它时,它会杀死 exe。

#include <windows.h>
int main() {
int i = 1;
int j = 3;
// refresh = time until refresh in minutes
int refresh = 10;
// 1000 milliseconds = 1 second
int second = 1000;
int minute = 60;
int time = second * minute * refresh;
while (i < j) {
system("cmd /c start /b SetWallpaper.exe /D:S Wallpaper.jpg");
Sleep(time);
}
return 0;
}

我尝试使用MinGW Msys附带的"sleep.exe",但它为每个团队创建了一个新流程,最终占用了所有流程。

提前感谢!

您遇到的第一个问题是,您已使用 main 方法将程序创建为控制台应用程序。 相反,请将其创建为具有WinMain入口点的Win32 Project。 这将直接调用,而无需创建控制台窗口。

编辑:第二个问题由Ferruccio的答案解决,因为您正在从您的控制台调用另一个控制台应用程序,这也将导致创建一个控制台窗口。

你正在以艰难的方式去做。在程序中更改Windows壁纸相当简单:

#include <windows.h>
SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, (PVOID) "path/to/wallpaper.jpg", SPIF_UPDATEINIFILE);

无论如何,如果您坚持启动外部程序来执行此操作。使用创建进程。它能够通过将dwCreationFlags参数设置为 CREATE_NO_WINDOW .

ShowWindow设置为false,不要忘记在最后FreeConsole

#include <windows.h>

int main(void)
{
   ShowWindow(FindWindowA("ConsoleWindowClass", NULL), false);
   // put your code here
   system("cmd /c start /b SetWallpaper.exe /D:S Wallpaper.jpg");
   FreeConsole();
   return 0;
}

正如Ferruccio所提到的,您可以使用SetTimerSystemParametersInfo来定期触发更改。

#define STRICT 1 
#include <windows.h>
#include <iostream.h>
VOID CALLBACK TimerProc(HWND hWnd, UINT nMsg, UINT nIDEvent, DWORD dwTime) 
{
  LPWSTR wallpaper_file = L"C:\Wallpapers\wallpaper.png";
  int return_value = SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, wallpaper_file, SPIF_UPDATEINIFILE);

  cout << "Programmatically change the desktop wallpaper periodically: " << dwTime << 'n';
  cout.flush();
}
int main(int argc, char *argv[], char *envp[]) 
{
    int Counter=0;
    MSG Msg;
    UINT TimerId = SetTimer(NULL, 0, 2000, &TimerProc); //2000 milliseconds = change every 2 seconds
    cout << "TimerId: " << TimerId << 'n';
   if (!TimerId)
    return 16;
   while (GetMessage(&Msg, NULL, 0, 0)) 
   {
        ++Counter;
        if (Msg.message == WM_TIMER)
        cout << "Counter: " << Counter << "; timer messagen";
        else
        cout << "Counter: " << Counter << "; message: " << Msg.message << 'n';
        DispatchMessage(&Msg);
    }
   KillTimer(NULL, TimerId);
return 0;
}