zoukankan      html  css  js  c++  java
  • 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();

  • 相关阅读:
    sql优化
    什么是泛型
    Http Status 400
    Hadoop搭建伪分布式 & 上传和下载文件
    Centos64 安装指南
    个人感悟
    zabbix4.0部署
    MySQL引擎
    mysql正则表达式
    k8s自动补全命令
  • 原文地址:https://www.cnblogs.com/514687800/p/3043672.html
Copyright © 2011-2022 走看看