Share via


Hosting Python in an Avalon TextBox

The PythonProcessor class from my last post is designed to be hosted in an GUI text editor.  I used an Avalon TextBox, as so:

namespace AddInConsole
{
     using System;
     using System.Globalization;
     using System.IO;
     using System.Text;
     using System.Windows;
     using System.Windows.Controls;
     using System.Windows.Input;
 
     public class ConsolePane : DockPanel
     {
          private TextBox textBox = null;
          private PythonProcessor processor = null;
 
          public ConsolePane()
          {
              this.textBox = new TextBox();
              this.textBox.AcceptsTab = true;
              this.textBox.KeyDown += textBox_KeyDown;
              this.Children.Add(this.textBox);
 
              TextBoxStream stream = new TextBoxStream(this.textBox);
              this.processor = new PythonProcessor(stream);
          }
 
          public PythonProcessor Processor
          {
              get
              {
                   return this.processor;
              }
          }
 
          void textBox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
          {
              if (e.Key == Key.Return)
              {
                   string line = this.textBox.GetLineText(this.textBox.LineCount - 1);
                   this.Write("\n");
                   if (this.processor.EvaluateLine(line))
                   {
                        this.Write("\n");
                   }
              }
          }
 
          internal void Clear()
          {
              if (this.textBox != null)
              {
                   this.textBox.Text = string.Empty;
              }
          }
 
          internal void Write(string run)
          {
              bool cursorIsAtEnd = false;
              if (this.textBox.SelectionStart == this.textBox.Text.Length)
              {
                   cursorIsAtEnd = true;
              }
 
              this.textBox.AppendText(run);
 
              if (cursorIsAtEnd)
              {
                   this.textBox.Select(this.textBox.Text.Length, 0);
                   this.textBox.ScrollToEnd();
              }
          }
 
          internal void WriteLine(string line)
          {
              this.Write(line + "\n");
          }
     }
}

Comments