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

时间:2014-10-22 19:04:05

标签: c# unmanaged

我有以下代码,从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()));
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

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