【问题标题】:Allocate Console to WinForm将控制台分配给 WinForm
【发布时间】:2018-09-10 06:56:48
【问题描述】:

我正在分配和释放 WinForm 应用程序中的控制台。第一次运行良好,但是当我运行 FreeConsole() 并再次运行 AllocConsole 时,它给了我 Exception Handle not Supported

分配和释放控制台的代码...

    [DllImport("kernel32.dll", SetLastError = true)]
    static extern int AllocConsole();

    [DllImport("kernel32.dll", SetLastError = true)]
    static extern int FreeConsole();

之后我在我的代码中使用这些函数,例如:

private void BtnSave_Click(object sender, EventArgs e)
    {
        if (CB_Branches.SelectedItem == null)
        {
            PopUp.Show(new Response() { Type = "error", Message = "Please select a branch.", Title = "Branch Missing!" });
            return;
        }

        try
        {
            readexcel();
            Console.WriteLine("============ Operation Complete!!! ============");
            Console.WriteLine();
            Console.WriteLine("============ Press any key to continue ============");
            Console.ReadKey();
            FreeConsole();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

readExcel()

public void readexcel() {
        bool err2 = false;
        try {
            FileInfo file = new FileInfo(txtPath.Text);
            Cursor.Current = Cursors.WaitCursor;
            using (ExcelPackage package = new ExcelPackage(file))
            {
                ExcelWorksheet workSheet = package.Workbook.Worksheets.First();
                int totalRows = workSheet.Dimension.Rows;
                progressBar1.Value = 0;
                Item itm = new Item();
                AllocConsole();
                Console.WriteLine("================= Adding Items (Inprogress...) ==================");
                for (int i = 2; i <= totalRows; i++)
                {
                    if (workSheet.Cells[i, 1].Value != null)
                    {
                        itm.Name = workSheet.Cells[i, 1].Value.ToString().ToUpper().Trim();

                        if (workSheet.Cells[i, 2].Value != null)
                        {
                            itm.Name = itm.Name + "_" + workSheet.Cells[i, 2].Value.ToString().ToUpper().Trim();
                        }
                    }
                    else
                    {
                        err2 = true;
                        Console.WriteLine( i + " =========># row Failed to save");
                        continue;
                    }

                    if (workSheet.Cells[i, 3].Value != null)
                    {
                        int ct = itmCatService.GetIdByName(workSheet.Cells[i, 3].Value.ToString());
                        if (ct == 0)
                        {
                            err2 = true;
                            Console.WriteLine(itm.Name + " =========> Failed to save");
                            continue;
                        }
                        else
                            itm.ItemCategoryId = ct;
                    }
                    else{
                        continue; 
                    }

                    if (workSheet.Cells[i, 4].Value != null)
                    {
                        itm.SalePrice = Convert.ToInt32(decimal.Parse(workSheet.Cells[i, 4].Value.ToString()));
                    }
                    else
                    {
                        err2 = true;
                        Console.WriteLine(itm.Name + " =========> Failed to save");
                        continue;
                    }

                    if (workSheet.Cells[i, 5].Value != null)
                    {
                        itm.TradePrice = Convert.ToInt32(decimal.Parse(workSheet.Cells[i, 5].Value.ToString()) );
                    }
                    else
                    {
                        err2 = true;
                        Console.WriteLine(itm.Name + " =========> Failed to save");
                        continue;
                    }

                    if (workSheet.Cells[i, 6].Value != null)
                    {
                        itm.ReorderLevel = int.Parse( workSheet.Cells[i, 6].Value.ToString() );
                    }
                    else
                    {
                        err2 = true;
                        Console.WriteLine(itm.Name + " =========> Failed to save");
                        continue;
                    }

                    if (workSheet.Cells[i, 7].Value != null)
                    {
                        itm.StockAmount = Convert.ToInt32(decimal.Parse(workSheet.Cells[i, 7].Value.ToString()));
                    }
                    else
                    {
                        err2 = true;
                        Console.WriteLine(itm.Name + " =========> Failed to save");
                        continue;
                    }

                    if (workSheet.Cells[i, 8].Value != null)
                    {
                        itm.Units = int.Parse(workSheet.Cells[i, 8].Value.ToString());
                    }
                    else
                    {
                        err2 = true;
                        Console.WriteLine(itm.Name + " =========> Failed to save");
                        continue;
                    }

                    if (workSheet.Cells[i, 9].Value != null)
                    {
                        int st = schoolService.GetIdByName(workSheet.Cells[i, 9].Value.ToString(), ((IdNameViewModel)CB_Branches.SelectedItem).Id);
                        if (st == 0)
                        {
                            err2 = true;
                            Console.WriteLine(itm.Name + " =========> Failed to save");
                            continue;
                        }
                        else
                            itm.SchoolId = st;
                    }
                    else
                    {
                        err2 = true;
                        Console.WriteLine(itm.Name + " =========> Failed to save");
                        continue;
                    }

                    itm.CreatedBy = UserDetails.UserId;
                    itm.Created = DateTime.Now;
                    itm.BranchId = ((IdNameViewModel)CB_Branches.SelectedItem).Id;

                    var res = itmService.CreateItem(itm);
                    if (res.Type.Equals("error") || res.Type.Equals("invalid"))
                    {
                        err2 = true;
                        Console.WriteLine(itm.Name+" =========> Failed to save");
                    }

                    progressBar1.Value = (i * 100) / totalRows; 
                }

                Cursor.Current = Cursors.Default;
                if (err2)
                {
                    MessageBox.Show("Some Items skipped or failed to save.!", "Operation Complete!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else
                {
                    MessageBox.Show("Items Created!", "Successful!", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }

        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);

        }
    }

在调试时,我知道调用Console.WriteLine(); 一次使用FreeConsole(); 会报错。

【问题讨论】:

  • 请创建一个minimal reproducible example。只需调用AllocConsole(); FreeConsole(); AllocConsole(); 即可。
  • @CodeCaster,添加详细代码。
  • 就像一个想法,单独的逻辑:在 readexcel() 方法之外调用 AllocConsole() 。谁能猜到“readexcel”会打开一个控制台?
  • @nabuchodonossor,建议注明。但它仍然不是获得异常的原因。
  • 有人回复吗?

标签: .net winforms console


【解决方案1】:

所以添加了更多代码,现在它工作正常......

第一个添加了一个函数并调用它而不是AllocConsole();

    public static void CreateConsole()
    {
        AllocConsole();
        // reopen stdout
        TextWriter writer = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = true };
        Console.SetOut(writer);
    }

然后在Console.Read();之前我加了一行

Console.SetIn(new StreamReader(Console.OpenStandardInput()));

现在它工作正常。

【讨论】:

    猜你喜欢
    • 2011-01-21
    • 2012-03-04
    • 1970-01-01
    • 1970-01-01
    • 2013-02-02
    • 1970-01-01
    • 1970-01-01
    • 2015-02-06
    • 2016-12-28
    相关资源
    最近更新 更多