将控制台分配给WinForm

时间:2018-09-10 06:56:48

标签: .net winforms console

我正在分配和释放 WinForm 应用程序中的控制台。第一次运行正常,但是当我运行FreeConsole()并再次运行AllocConsole时,它给了我异常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();会给我带来错误。

1 个答案:

答案 0 :(得分:1)

因此添加了更多代码,现在可以正常工作了。...

1st添加了一个函数并调用了它,而不是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()));

现在可以正常工作了。