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();

  • 相关阅读:
    [IDA] Oops! internal error 40343 occured.
    内核空间与内核模块
    Windows下如何调试驱动程序
    关于SQL Server中的系统表之一 sysobjects
    Sql Server 存储过程中查询数据无法使用 Union(All)
    Sql Server 存储过程分页
    Javascript转义字符串中的特殊字符处理
    IIS7部署报错 500.22错误 检查到这集成托管模式下不使用的ASP.NET配置
    Visio制图之垮职能流程图
    saltstack的配置使用
  • 原文地址:https://www.cnblogs.com/514687800/p/3043672.html
Copyright © 2011-2022 走看看