如何隐藏控制台窗口

本文关键字:控制台 窗口 隐藏 何隐藏 | 更新日期: 2023-09-27 18:11:13

csharp不是我的母语,但我正试图了解如何改变我的csharp代码,以便在我运行可执行文件时不出现控制台窗口。

我使用的代码是:

using System;
using System.Runtime.InteropServices;
using System.Text;
using System.IO;
using System.Threading;
namespace Foreground {
  class GetForegroundWindowTest {
    [DllImport("user32.dll", CharSet=CharSet.Auto, ExactSpelling=true)]
    public static extern IntPtr GetForegroundWindow();
    [DllImport("user32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
    public static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
    public static void Main(string[] args){
        while (true){
            IntPtr fg = GetForegroundWindow(); //use fg for some purpose
            var bufferSize = 1000;
            var sb = new StringBuilder(bufferSize);
            GetWindowText(fg, sb, bufferSize);
            using (StreamWriter sw = File.AppendText("C:''Office Viewer''OV_Log.txt")) 
            {
                sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd_HH:mm:ss,") + sb.ToString());
            }
            Thread.Sleep(5000);
        }
    }
  }
}

我的失败尝试是:

using System;
using System.Runtime.InteropServices;
using System.Text;
using System.IO;
using System.Threading;
namespace Foreground {
  class GetForegroundWindowTest {
    /// Foreground dll's
    [DllImport("user32.dll", CharSet=CharSet.Auto, ExactSpelling=true)]
    public static extern IntPtr GetForegroundWindow();
    [DllImport("user32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
    public static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
    /// Console hide dll's
    [DllImport("kernel32.dll")]
    static extern IntPtr GetConsoleWindow();
    [DllImport("user32.dll")]
    static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
    const int SW_HIDE = 0;
    public static void Main(string[] args){
        while (true){
            IntPtr fg = GetForegroundWindow(); //use fg for some purpose
            var bufferSize = 1000;
            var sb = new StringBuilder(bufferSize);
            GetWindowText(fg, sb, bufferSize);
            using (StreamWriter sw = File.AppendText("C:''Office Viewer''OV_Log.txt")) 
            {
                sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd_HH:mm:ss,") + sb.ToString());
            }
            var handle = GetConsoleWindow();
            ShowWindow(handle, SW_HIDE);
            Thread.Sleep(5000);
        }
    }
  }
}

如何隐藏控制台窗口

在项目属性中选择Windows Application而不是Console Application