Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
445 views
in Technique[技术] by (71.8m points)

.net - How do I add a console like element to a c# winforms program

I have a program that monitors debug messages and I have tried using a TextBox and appended the messages to it but it doesn't scale very well and slows way down when the number of messages gets large. I then tried a ListBox but the scrolling was snapping to the top when appending new messages. It also doesn't allow for cut and paste like the text box does.

What is a better way to implement a console like element embedded in a winforms window.

Edit: I would still like to be able to embed a output window like visual studio but since I can't figure out an easy way here are the two solutions I use. In addition to using the RichTextBox which works but you have to clear it every now and then. I use a console that I pinvoke. Here is a little wrapper class that I wrote to handle this.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace Con
{
   class Ext_Console 
   {
      static bool console_on = false;

      public static void Show(bool on,string title)
      {
         console_on = on;
         if (console_on)
         {
            AllocConsole();
            Console.Title = title;
            // use to change color
            Console.BackgroundColor = System.ConsoleColor.White;
            Console.ForegroundColor = System.ConsoleColor.Black;

         }
         else
         {
            FreeConsole();
         }
      }

      public static void Write(string output)
      {
         if (console_on)
         {
            Console.Write(output);
         }
      }

      public static void WriteLine(string output)
      {
         if (console_on)
         {
            Console.WriteLine(output);
         }
      }

      [DllImport("kernel32.dll")]
      public static extern Boolean AllocConsole();
      [DllImport("kernel32.dll")]
      public static extern Boolean FreeConsole();
   }
}


// example calls
Ext_Console.Write("console output  ");
Ext_Console.WriteLine("console output");
Ext_Console.Show(true,"Title of console");


See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

RichTextBox has an AppendText method that is fast. And it can handle large text well.
I believe it is the best for what you need.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...