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

本文关键字:AddConsoleAlias 不起作用 调用 非托管代码 | 更新日期: 2023-09-27 18:27:25

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

8明显为CCD_ 2。

我当然有足够的记忆力,但这个过程并不这么认为,有人能告诉我可能出了什么问题吗?

当然,除了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()));
            }
        }
    }
}

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

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