C# 将输出打印到cmd

C# 将输出打印到cmd,c#,cmd,output,C#,Cmd,Output,请有人提供一个工作示例,说明我如何将变量fg打印到命令行 using System; using System.Runtime.InteropServices; using System.Text; namespace Foreground { class GetForegroundWindowTest { [DllImport("user32.dll", CharSet=CharSet.Auto, ExactSpelling=true)] public static e

请有人提供一个工作示例,说明我如何将变量fg打印到命令行

using System;
using System.Runtime.InteropServices;
using System.Text;

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){
        IntPtr fg = GetForegroundWindow(); //use fg for some purpose

        /// PRINT fg TO COMMAND LINE

    }
  }
}
项目的一部分,需要将其用于:

cs文件将在cmd中编译和运行。该程序将检索用户前景窗口的名称,并将该窗口的标题输出到cmd

我试过:

Console.WriteLine(fg)

你可以用

Console.WriteLine(fg); 

问题不是很清楚,但我想你是想这么做的:

IntPtr fg = GetForegroundWindow(); //use fg for some purpose

var bufferSize = 1000;
var sb = new StringBuilder(bufferSize);

GetWindowText(fg, sb, bufferSize);

Console.WriteLine(sb.ToString());

控制台。写入线(前景)。虽然您可能有一个GUI应用程序,但没有打开任何控制台窗口。上次我看的时候,它太复杂了,我无法打开它。您最好使用文本框或包含该文本的对话框。这个问题没有显示任何研究成果。查看GetWindowText(),我几乎担心OP希望将文本转储到窗口上,而不是窗口本身。罗伯特,请清楚地描述一下你的设置是什么,程序做什么,你想实现什么,你尝试了什么,以及失败的方式。“将fg打印到命令行”和“是否有人可以为我提供一个工作示例”是不够的。Console.WriteLine(fg)不会打印到命令行。为什么会这样?什么是“命令行”?您正在调试器中运行吗?你有窗户吗?窗户开着吗?你到底在窗户下面吗??请在您的描述中清晰完整。感谢所有回答我的人,我希望在CMD上打印输出。这个错误是我的一个noob错误——我希望在编译阶段看到命令行输出,而不是在.exe阶段。我为你的困惑道歉,因为我的困惑。
System.Diagnostics.Process.Start("CMD.exe",fg);
IntPtr fg = GetForegroundWindow(); //use fg for some purpose

var bufferSize = 1000;
var sb = new StringBuilder(bufferSize);

GetWindowText(fg, sb, bufferSize);

Console.WriteLine(sb.ToString());