Forms and Console

烂漫一生 提交于 2020-01-07 05:30:31

问题


I'm Running a forms application and a console application in one application.

How can i run the forms application and keep the console closed until i click a button on the form?


回答1:


You need to call a couple of win32app calls most specifically allocconsole. here is an msdn post with some sample code.




回答2:


You'll need to do a little P/Invoke:

Add the appropriate methods:

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.");
        }
    }
}


来源:https://stackoverflow.com/questions/9426007/forms-and-console

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!