繁体   English   中英

C#非托管代码调用不起作用:AddConsoleAlias

[英]C# unmanaged code call not working: AddConsoleAlias

我有以下代码,该代码不断从GetLastError()调用返回值为8的FALSE。

8显然是ERROR_NOT_ENOUGH_MEMORY

我当然有足够的记忆力,但是过程却不这么认为,任何人都可以启发我发生什么问题吗?

下面的代码是我除了Forms对象声明之外的全部代码,但是我想没有必要看到它,因为我有2个文本框和1个按钮。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace AddConsoleAlias
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        [DllImport("kernel32", SetLastError = true)]
        static extern bool AddConsoleAlias(string Source, string Target, string ExeName);

        [DllImport("kernel32.dll")]
        static extern uint GetLastError();

        private void btnAddAlias_Click(object sender, EventArgs e)
        {
            if (AddConsoleAlias(txbSource.Text, txbTarget.Text, "cmd.exe"))
            {
                MessageBox.Show("Success");
            }
            else
            {
                MessageBox.Show(String.Format("Problem occured - {0}", GetLastError()));
            }
        }
    }
}

AddConsoleAlias定义控制台别名。 您有Windows窗体应用程序,而没有打开控制台。 应该在AddConsoleAlias调用之前分配控制台。 为此,您可以使用AllocConsole函数。

此功能的C#绑定是:

[DllImport("kernel32.dll", 
        EntryPoint = "AllocConsole",
        SetLastError = true,
        CharSet = CharSet.Auto,
        CallingConvention = CallingConvention.StdCall)]
    private static extern int AllocConsole();

您修改后的代码如下所示:

  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
    }

    [DllImport("kernel32.dll", 
        EntryPoint = "AllocConsole",
        SetLastError = true,
        CharSet = CharSet.Auto,
        CallingConvention = CallingConvention.StdCall)]
    private static extern int AllocConsole();

    [DllImport("kernel32", SetLastError = true)]
    static extern bool AddConsoleAlias(string Source, string Target, string ExeName);

    [DllImport("kernel32.dll")]
    static extern uint GetLastError();

    private void btnAddAlias_Click(object sender, EventArgs e)
    {
      AllocConsole();

      if (AddConsoleAlias(txbSource.Text, txbTarget.Text, "cmd.exe"))
      {
        MessageBox.Show("Success");
      }
      else
      {
        MessageBox.Show(String.Format("Problem occured - {0}", GetLastError()));
      }
    }
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM