簡體   English   中英

調用C++ dll的方法在C# app打開console window,如何抑制console?

[英]Call of a method from C++ dll opens console window in C# app, how do I suppress the console?

我已經用一個已發布的方法編寫了一個 C++ dll,它只是用一個定義的參數啟動另一個程序。 從 C# WinForms 應用程序調用此方法。

單擊按鈕從 C# 應用程序觸發已發布的方法。 第二個應用程序正在按預期啟動,但另外一個 Windows 控制台 window 正在打開,但不輸出任何內容。

我想抑制控制台 window,但我不知道該怎么做。 當我運行的應用程序終止時,控制台 window 也終止。

這是我的 header 和 C++ dll 的來源:

發射器.h

#pragma once

#ifdef ILJ16_EXPORTS
#define LAUNCHER_EXPORT __declspec(dllexport)
#else
#define LAUNCHER_EXPORT __declspec(dllimport)
#endif // ILJ16_EXPORTS

const char* startParam = "--Q7t0elSDASCrpHQ";

extern "C" LAUNCHER_EXPORT void startProcess();

發射器.cpp

#include "pch.h"
#include "launcher.h"
#include <process.h>
#include <stdio.h>

void startProcess()
{
    char command[256 + 1];
    snprintf(command, sizeof(command), "Test.exe %s", startParam); //Test.exe is the application which has to be started
    int retCode = system(command);
}

在我的 C# WinForms 項目中,我編寫了以下代碼

using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        [DllImport("ilj16.dll", EntryPoint = "startProcess")]
        public static extern void startProcess();
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            startProcess();
        }
    }
}

從閱讀 windows 文檔可以看出, system(const char*)調用會打開 cmd.exe 提示符,然后執行該字符串。

系統文檔

系統 function 將命令傳遞給命令解釋器,命令解釋器將字符串作為操作系統命令執行。 系統使用 COMSPEC 和 PATH 環境變量來定位命令解釋器文件 CMD.exe。 如果命令是 NULL,function 只是檢查命令解釋器是否存在。

從快速谷歌看起來解決這個問題的最好方法是使用_popenCreateProcessA ,或者你可以嘗試使用類似這樣的東西隱藏/關閉 cmd.exe 。

此外,如果您的 C++ dll 只是打開另一個程序,您可以消除對 dll 的需要,並在 C# 中使用此 C# class完成所有操作。 在該鏈接的第一個示例中,有一個簡單的解決方案:

    using (Process myProcess = new Process())
    {
        myProcess.StartInfo.UseShellExecute = false;
        // You can start any process, HelloWorld is a do-nothing example.
        myProcess.StartInfo.FileName = "C:\\HelloWorld.exe";
        myProcess.StartInfo.CreateNoWindow = true;
        myProcess.Start();
        // This code assumes the process you are starting will terminate itself.
        // Given that is is started without a window so you cannot terminate it
        // on the desktop, it must terminate itself or you can do it programmatically
        // from this application using the Kill method.
    }

而不是startprocess ,考慮使用CreateProcess並將STARTUPINFO.wShowWindow設置為SW_HIDE

CreateProcess

創建一個新進程及其主線程。 新進程在調用進程的安全上下文中運行

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM