如何在windows服务中启动控制台屏幕

本文关键字:启动 控制台 屏幕 服务 windows | 更新日期: 2023-09-27 17:57:45

我使用Tow方法将我的应用程序(windows应用程序)记录到文件和控制台屏幕

public static void InitLogFile(string filename)
{
    FileStream fs = new FileStream(filename, FileMode.Create);
    Trace.Listeners.Add(new TextWriterTraceListener(fs));
    Trace.AutoFlush = true;
}
public static void InitConsole()
{
    Trace.Listeners.Add(new ConsoleTraceListener());
    Trace.AutoFlush = true;
}

当我的windows应用程序启动时,我用这个代码来启动控制台屏幕

  [DllImport("kernel32.dll",EntryPoint = "GetStdHandle",SetLastError = true,CharSet = CharSet.Auto,
        CallingConvention = CallingConvention.StdCall)]
        private static extern IntPtr GetStdHandle(int nStdHandle);
        [DllImport("kernel32.dll",EntryPoint = "AllocConsole",SetLastError = true,CharSet = CharSet.Auto,
        CallingConvention = CallingConvention.StdCall)]
        private static extern int AllocConsole();

        private const int STD_OUTPUT_HANDLE = -11;
        private const int MY_CODE_PAGE = 437;
        void StartConsole()
        {
            AllocConsole();
            IntPtr stdHandle = GetStdHandle(STD_OUTPUT_HANDLE);
            var safeFileHandle = new SafeFileHandle(stdHandle, true);
            var fileStream = new FileStream(safeFileHandle, FileAccess.Write);
            var encoding = Encoding.GetEncoding(MY_CODE_PAGE);
            var standardOutput = new StreamWriter(fileStream, encoding) {AutoFlush = true};
            Console.SetOut(standardOutput);
        }

我的问题是:

我将我的windows应用程序转换为windows service控制台日志屏幕不工作现在不显示如何使其工作?

如何在windows服务中启动控制台屏幕

Windows服务不像标准的Windows应用程序那样运行。它可能在没有用户登录计算机的情况下运行,那么控制台屏幕怎么会出现呢?

当作为服务运行时,您应该考虑写入Windows事件日志或其他日志记录机制。

您没有看到任何内容的原因是因为会话0隔离。

然而,有一篇很好的代码项目文章,它将在用户会话中从服务运行应用程序。

只需将代码放入一个exe文件中,然后使用链接中的项目启动exe文件。