c# WinForm调用控制台

由于Windows控制台程序是封装在kernel32.dll,所以有必要讲述一下WinForm如何调用动态链接库的步骤。

1.首先需要在调用窗体中申明using System.Runtime.InteropServices;

2.其次需要在C#语言源程序中声明外部方法,格式如下:

[DLLImport(“DLL文件”)]

修饰符 extern 返回变量类型 方法名称 (参数列表)

其中:DLL文件:包含定义外部方法的库文件;修饰符:访问修饰符,除了abstract以外在声明方法时可以使用的修饰符;返回变量类型:在DLL文件中你需调用方法的返回变量类型;方法名称:在DLL文件中你需调用方法的名称;参数列表:在DLL文件中你需调用方法的列表。

注意:外部方法的申明位置应该放在方法申明处,一般是放在类里的头部。

3.在调用出,直接调用方法即可。

下面以WinForm调用控制台程序进行举例说明:

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 System.Runtime.InteropServices;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        [DllImport("kernel32.dll")]
        public static extern bool AllocConsole();
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
                 
            AllocConsole();
            System.Console.WriteLine("CYY 你好!");        
        }
    }
}

 

附:其实调用控制台更多的是通过创建一个类来调用,原理是一样的,同样附上实例

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace WindowsFormsApplication1
{
    public class ConsoleShow
    {
        /// <summary>
        /// 启动控制台
        /// </summary>
        /// <returns></returns>
        [DllImport("kernel32.dll")]
        public static extern bool AllocConsole();
        /// <summary>
        /// 释放控制台
        /// </summary>
        /// <returns></returns>
        [DllImport("kernel32.dll")]
        public static extern bool FreeConsole();
    }
}

 

这个时候,在调用的时候ConsoleShow pConsoleShow = new ConsoleShow (); pConsoleShow .AllocConsole();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值