0
Q
窗体和控制台
A
回答
0
您需要调用几个win32app调用,特别是allocconsole。这里有一个msdn的帖子和一些示例代码。
0
你需要做一个小的P/Invoke:
添加适当的方法:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using StackOverflow.Extensions;
using System.Runtime.InteropServices;
using System.IO;
using Microsoft.Win32.SafeHandles;
namespace StackOverflow
{
public partial class FormMain : Form
{
[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();
// Some constants
private const int STD_OUTPUT_HANDLE = -11;
private const int MY_CODE_PAGE = 437;
public FormMain()
{
InitializeComponent();
}
public void PrepareConsole()
{
AllocConsole();
IntPtr stdHandle = GetStdHandle(STD_OUTPUT_HANDLE);
SafeFileHandle safeFileHandle = new SafeFileHandle(stdHandle, true);
FileStream fileStream = new FileStream(safeFileHandle, FileAccess.Write);
Encoding encoding = System.Text.Encoding.GetEncoding(MY_CODE_PAGE);
StreamWriter standardOutput = new StreamWriter(fileStream, encoding);
standardOutput.AutoFlush = true;
Console.SetOut(standardOutput);
}
private void button1_Click(object sender, EventArgs e)
{
// Console was not visible before this button click
Console.WriteLine("This text is written to the console that just popped up.");
MessageBox.Show("But we're still in a Windows Form application.");
}
}
}
相关问题
- 1. C#中的控制台和Windows窗体#
- 2. C#Windows窗体.Net和DOS控制台
- 3. 控制台的Windows窗体
- 4. 连接一个窗体与控制台
- 5. .NET:Windows窗体+控制台/合闸闭锁
- 6. Process.WaitForExit()在控制台VS Windows窗体
- 7. 将控制台appender添加到log4net中的窗体窗体
- 8. Windows窗体和控制台之间的沟通
- 9. 更新和多个控制台窗口
- 10. RStudio拆分控制台和源窗格
- 11. printf到控制台窗口和文件?
- 12. 控制PowerShell控制台窗口位置
- 13. 如何关闭窗体后关闭控制台窗口
- 14. 隐藏Windows窗体应用程序中的控制台窗口
- 15. Visual Studio控制台窗口
- 16. .NET控制台窗口
- 17. 隐藏控制台窗口
- 18. 检测控制台窗口?
- 19. 激活控制台窗口
- 20. Unkillable控制台窗口
- 21. 隐藏控制台窗口
- 22. AX 2012窗体控制和计算
- 23. C#控制台字体
- 24. 控制子窗体记录和选项卡控制页面?
- 25. 红宝石和GTK3在后台没有控制台窗口
- 26. 从控制台在Windows窗体中使用一个变量
- 27. 从Windows窗体运行控制台应用程序
- 28. 从控制台应用程序到Windows窗体GUI问题
- 29. 在控制台应用程序中的WPF窗体
- 30. 从控制台应用程序到.NET Windows窗体
我一直想知道为什么的CreateFile使用SafeFileHandle有返回值,但GetStdHandle没有。 – Rahly 2014-01-06 02:06:26
它一直在为我工作,但突然停下来,不知道为什么。其他人是否有反馈? – WSK 2016-08-18 16:41:49