打印输出到cmd

本文关键字:cmd 输出 打印 | 更新日期: 2023-09-27 18:10:25

有人可以提供一个工作的例子,我将如何打印到命令行变量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)

[DllImport( "kernel32.dll" )]
static extern bool AttachConsole( int dwProcessId );
private const int ATTACH_PARENT_PROCESS = -1;

打印输出到cmd

这个问题不是很清楚,但我假设您正在尝试这样做:

IntPtr fg = GetForegroundWindow(); //use fg for some purpose
var bufferSize = 1000;
var sb = new StringBuilder(bufferSize);
GetWindowText(fg, sb, bufferSize);
Console.WriteLine(sb.ToString());

可以使用

Console.WriteLine(fg); 
System.Diagnostics.Process.Start("CMD.exe",fg);