Cannot have 2 abstract-derived textboxes on the same WinForm? - winforms

OK, this is a weird problem. I have an abstract control that derives from TextBox called Writer, and two classes that derive from it, StdWriter and LngWriter. The difference between them is one is always multiline and the other is not. That's seriously the only difference between the two.
In the OnHandleCreated function, I set the margins with the Win32 SendMessage function. I do it again in OnPaint because WinForms will "forget" to set the margins if I have more than 1 StdWriter (or any derived textbox type) on the same form (this makes no sense either but at least I have a workaround for it).
Now I have the problem that I can't have both of these textboxes on the same form. If I put a StdWriter and a multiline TextBox or a LngWriter and a standard TextBox on the form, it works. If I put 2 MS textboxes on the form, it also works. but let me put a LngWriter and StdWriter together and the LngWriter won't draw its scrollbar right (the vertical is wrong and it just won't draw the horizontal, period) or accept the Enterkey, despite both MultiLine and AcceptsReturn returning true. I can't even paste newlines in because it totally strips them out.
I don't understand this because TextBox derives from the abstract TextBoxBase and I don't have any problems with dozens of different derived textboxes all over my forms. Is it because I'm inserting a second abstract class in the inheritance chain and Visual Studio doesn't like it or what?
public abstract class RKWRITER : System.Windows.Forms.TextBox
{
protected sealed class RKLAYOUT : System.Windows.Forms.TableLayoutPanel
protected sealed class RKFLIPPER : System.Windows.Forms.CheckBox
protected sealed class RKBITMAP : System.Windows.Forms.PictureBox
protected RKSHARP2.Controls.RKWRITER.RKLAYOUT Control_Secondary = null;
protected RKSHARP2.Controls.RKWRITER.RKBITMAP Control_IconView = null;
protected RKSHARP2.Controls.RKWRITER.RKFLIPPER Control_NullView = null;
public override System.Boolean Multiline
{
get
{
return base.Multiline;
}
set
{
this.SuspendLayout();
base.Multiline = value;
this.RecreateHandle();
this.ResumeLayout();
this.PerformLayout();
this.Invalidate();
}
}
protected static void SetControlBuffer (System.IntPtr Pointer_Control, System.Int32 Integer_West, System.Int32 Integer_East)
{
RKSHARP2.System.Internal.USER32.SendMessage(Pointer_Control, RKSHARP2.System.Internal.USER32.EM_SETMARGINS, new System.IntPtr(RKSHARP2.System.Internal.USER32.EC_LEFTMARGIN|RKSHARP2.System.Internal.USER32.EC_RIGHTMARGIN), new System.IntPtr((0x00010000 * Integer_East) + Integer_West));
}
}
public sealed class RKSTANDARDWRITER : RKSHARP2.Controls.RKWRITER
{
public override System.Boolean Multiline
{
get
{
return false;
}
set
{
this.SuspendLayout();
base.Multiline = false;
this.RecreateHandle();
this.ResumeLayout();
this.PerformLayout();
this.Invalidate();
}
}
public RKSTANDARDWRITER ()
{
this.SuspendLayout();
this.AcceptsReturn = false;
this.AcceptsTab = false;
this.AutoSize = false;
this.DoubleBuffered = true;
this.Margin = new System.Windows.Forms.Padding(0);
this.MaxLength = 24;
this.Multiline = false;
this.Padding = new System.Windows.Forms.Padding(0);
this.PasswordChar = RKSHARP2.Constants.NULLZERO;
this.ResizeRedraw = true;
this.ScrollBars = System.Windows.Forms.ScrollBars.None;
this.Text = null;
this.UseSystemPasswordChar = false;
this.Vertical = 1;
this.Visible = true;
this.WordWrap = false;
this.SetControlProperties(null, false, new System.Drawing.Size(0, 0), null, false, true);
this.ResumeLayout();
this.PerformLayout();
}
#pragma warning disable 1591
protected override void OnHandleCreated (System.EventArgs Object_Arguments)
{
base.OnHandleCreated(Object_Arguments);
this.ClientSize = new System.Drawing.Size(this.ClientSize.Width, System.Math.Max(this.FontHeight, this.Control_Secondary.PreferredSize.Height) * this.Vertical);
RKSHARP2.Controls.RKSTANDARDWRITER.SetControlBuffer(this.Handle, this.Control_Secondary.PreferredSize.Width, 0);
}
protected override void OnPaint (System.Windows.Forms.PaintEventArgs Object_Arguments)
{
//RRK: I have no idea WTF is suddenly wrong here but Windows will not set margins in OnHandleCreated() if multiple controls are present.
base.OnPaint(Object_Arguments);
RKSHARP2.Controls.RKSTANDARDWRITER.SetControlBuffer(this.Handle, this.Control_Secondary.PreferredSize.Width, 0);
}
protected override void WndProc (ref System.Windows.Forms.Message Object_Message)
{
#pragma warning disable 0162
switch (Object_Message.Msg)
{
default:
{
base.WndProc(ref Object_Message);
}
break;
}
#pragma warning restore 0162
}
public override System.Drawing.Size MinimumSize
{
get
{
return RKSHARP2.Windows.WindowSystemController.CompareMaximumSizes(base.MinimumSize, this.SizeFromClientSize(new System.Drawing.Size(this.Control_Secondary.PreferredSize.Width, System.Math.Max(this.FontHeight, this.Control_Secondary.PreferredSize.Height))));
}
set
{
base.MinimumSize = value;
}
}
public override System.Drawing.Size MaximumSize
{
get
{
return base.MaximumSize;
}
set
{
base.MaximumSize = value;
}
}
public override System.Drawing.Size GetPreferredSize (System.Drawing.Size Struct_Proposed)
{
return base.GetPreferredSize(Struct_Proposed);
}
protected void SetControlProperties (System.String String_Startup, System.Boolean Boolean_IconView, System.Drawing.Size Struct_IconSize, System.Drawing.Bitmap Object_Bitmap, System.Boolean Boolean_NullView, System.Boolean Boolean_NullType)
{
this.Control_Secondary = new RKSHARP2.Controls.RKSTANDARDWRITER.RKLAYOUT();
this.Control_Secondary.AutoSize = true;
this.Control_Secondary.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.Control_Secondary.BackColor = System.Drawing.Color.Transparent;
this.Control_Secondary.BackgroundImage = null;
this.Control_Secondary.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None;
this.Control_Secondary.CellBorderStyle = System.Windows.Forms.TableLayoutPanelCellBorderStyle.None;
this.Control_Secondary.ColumnCount = 4;
this.Control_Secondary.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100));
this.Control_Secondary.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.AutoSize, 0));
this.Control_Secondary.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.AutoSize, 0));
this.Control_Secondary.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100));
this.Control_Secondary.Dock = System.Windows.Forms.DockStyle.Left;
this.Control_Secondary.GrowStyle = System.Windows.Forms.TableLayoutPanelGrowStyle.FixedSize;
this.Control_Secondary.Margin = new System.Windows.Forms.Padding(0);
this.Control_Secondary.Padding = new System.Windows.Forms.Padding(0);
this.Control_Secondary.RowCount = 3;
this.Control_Secondary.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100));
this.Control_Secondary.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.AutoSize, 0));
this.Control_Secondary.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100));
this.Control_Secondary.Size = new System.Drawing.Size(0, 0);
this.Control_Secondary.TabIndex = 0;
this.Control_Secondary.TabStop = false;
this.Control_Secondary.Visible = true;
this.Control_IconView = new RKSHARP2.Controls.RKSTANDARDWRITER.RKBITMAP();
this.Control_IconView.AutoSize = false;
this.Control_IconView.BackColor = System.Drawing.Color.Transparent;
this.Control_IconView.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.Control_IconView.Cursor = System.Windows.Forms.Cursors.Default;
this.Control_IconView.Dock = System.Windows.Forms.DockStyle.Fill;
this.Control_IconView.Image = Object_Bitmap;
this.Control_IconView.Margin = new System.Windows.Forms.Padding(0);
this.Control_IconView.Padding = new System.Windows.Forms.Padding(0);
this.Control_IconView.Parent = this;
this.Control_IconView.Size = Struct_IconSize;
this.Control_IconView.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.Control_IconView.TabIndex = 0;
this.Control_IconView.TabStop = false;
this.Control_IconView.Visible = Boolean_IconView;
this.Control_IconView.VisibleChanged += new System.EventHandler(delegate(System.Object Object_Sender, System.EventArgs Object_Arguments){this.Control_IconView.Parent.Visible=this.IconView||this.NullView;});
this.Control_NullView = new RKSHARP2.Controls.RKSTANDARDWRITER.RKFLIPPER();
this.Control_NullView.AutoSize = true;
this.Control_NullView.BackColor = System.Drawing.Color.Transparent;
this.Control_NullView.Checked = true;
this.Control_NullView.Cursor = System.Windows.Forms.Cursors.Default;
this.Control_NullView.Dock = System.Windows.Forms.DockStyle.Fill;
this.Control_NullView.Enabled = !this.ReadOnly;
this.Control_NullView.Margin = new System.Windows.Forms.Padding(0);
this.Control_NullView.Padding = new System.Windows.Forms.Padding(0);
this.Control_NullView.Parent = this;
this.Control_NullView.Size = new System.Drawing.Size(0, 0);
this.Control_NullView.TabIndex = 0;
this.Control_NullView.TabStop = false;
this.Control_NullView.Text = "";
this.Control_NullView.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
this.Control_NullView.UseVisualStyleBackColor = true;
this.Control_NullView.Visible = Boolean_NullView;
this.Control_NullView.CheckedChanged += new System.EventHandler(delegate(System.Object Object_Sender, System.EventArgs Object_Arguments){this.ReadOnly=!this.Control_NullView.Checked;});
this.Control_NullView.VisibleChanged += new System.EventHandler(delegate(System.Object Object_Sender, System.EventArgs Object_Arguments){this.Control_NullView.Parent.Visible=this.NullView||this.IconView;});
this.Control_Secondary.SuspendLayout();
this.Control_Secondary.Controls.Add(RKSHARP2.Controls.RKSTANDARDWRITER.ConstructContainer(this.Control_IconView), 1, 1);
this.Control_Secondary.Controls.Add(RKSHARP2.Controls.RKSTANDARDWRITER.ConstructContainer(this.Control_NullView), 2, 1);
this.Control_Secondary.ResumeLayout();
this.Control_Secondary.PerformLayout();
this.Controls.Add(this.Control_Secondary);
}
protected static RKSHARP2.Controls.RKSTANDARDWRITER.RKLAYOUT ConstructContainer (System.Windows.Forms.Control Control_Temporary)
{
RKSHARP2.Controls.RKSTANDARDWRITER.RKLAYOUT Control_Container = new RKSHARP2.Controls.RKSTANDARDWRITER.RKLAYOUT();
Control_Container.SuspendLayout();
Control_Container.AutoSize = true;
Control_Container.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
Control_Container.BackColor = System.Drawing.Color.Transparent;
Control_Container.BackgroundImage = null;
Control_Container.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None;
Control_Container.CellBorderStyle = System.Windows.Forms.TableLayoutPanelCellBorderStyle.None;
Control_Container.ColumnCount = 3;
Control_Container.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100));
Control_Container.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.AutoSize, 0));
Control_Container.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100));
Control_Container.Dock = System.Windows.Forms.DockStyle.Fill;
Control_Container.GrowStyle = System.Windows.Forms.TableLayoutPanelGrowStyle.FixedSize;
Control_Container.Margin = new System.Windows.Forms.Padding(2);
Control_Container.Padding = new System.Windows.Forms.Padding(0);
Control_Container.RowCount = 3;
Control_Container.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100));
Control_Container.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.AutoSize, 0));
Control_Container.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100));
Control_Container.Size = new System.Drawing.Size(0, 0);
Control_Container.TabIndex = 0;
Control_Container.TabStop = false;
Control_Container.Visible = Control_Temporary.Visible;
Control_Container.Controls.Add(Control_Temporary, 1, 1);
Control_Container.ResumeLayout();
Control_Container.PerformLayout();
return Control_Container;
}
protected static void SetControlBuffer (System.IntPtr Pointer_Control, System.Int32 Integer_West, System.Int32 Integer_East)
{
RKSHARP2.Controls.RKWRITER.SetControlBuffer(Pointer_Control, Integer_West, Integer_East);
}
#pragma warning restore 1591
}
public sealed class RKQUESTIONWRITER : RKSHARP2.Controls.RKWRITER
{
public override System.Boolean Multiline
{
get
{
return true;
}
set
{
this.SuspendLayout();
base.Multiline = true;
this.RecreateHandle();
this.ResumeLayout();
this.PerformLayout();
this.Invalidate();
}
}
public RKQUESTIONWRITER ()
{
this.SuspendLayout();
this.AcceptsReturn = true;
this.AcceptsTab = true;
this.AutoSize = true;
this.DoubleBuffered = true;
this.Margin = new System.Windows.Forms.Padding(0);
this.MaxLength = 32768;
this.Multiline = true;
this.Padding = new System.Windows.Forms.Padding(0);
this.PasswordChar = RKSHARP2.Constants.NULLZERO;
this.ResizeRedraw = true;
this.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.Text = null;
this.UseSystemPasswordChar = false;
this.Vertical = 8;
this.Visible = true;
this.WordWrap = true;
this.SetControlProperties(null, false, new System.Drawing.Size(0, 0), null, false, true);
this.ResumeLayout();
this.PerformLayout();
}
#pragma warning disable 1591
protected override void OnHandleCreated (System.EventArgs Object_Arguments)
{
base.OnHandleCreated(Object_Arguments);
this.ClientSize = new System.Drawing.Size(this.ClientSize.Width, System.Math.Max(this.FontHeight, this.Control_Secondary.PreferredSize.Height) * this.Vertical);
RKSHARP2.Controls.RKQUESTIONWRITER.SetControlBuffer(this.Handle, this.Control_Secondary.PreferredSize.Width, 0);
}
protected override void OnPaint (System.Windows.Forms.PaintEventArgs Object_Arguments)
{
//RRK: I have no idea WTF is suddenly wrong here but Windows will not set margins in OnHandleCreated() if multiple controls are present.
base.OnPaint(Object_Arguments);
RKSHARP2.Controls.RKQUESTIONWRITER.SetControlBuffer(this.Handle, this.Control_Secondary.PreferredSize.Width, 0);
}
protected override void WndProc (ref System.Windows.Forms.Message Object_Message)
{
#pragma warning disable 0162
switch (Object_Message.Msg)
{
default:
{
base.WndProc(ref Object_Message);
}
break;
}
#pragma warning restore 0162
}
public override System.Drawing.Size MinimumSize
{
get
{
return RKSHARP2.Windows.WindowSystemController.CompareMaximumSizes(base.MinimumSize, this.SizeFromClientSize(new System.Drawing.Size(this.Control_Secondary.PreferredSize.Width, System.Math.Max(this.FontHeight, this.Control_Secondary.PreferredSize.Height))));
}
set
{
base.MinimumSize = value;
}
}
public override System.Drawing.Size MaximumSize
{
get
{
return base.MaximumSize;
}
set
{
base.MaximumSize = value;
}
}
public override System.Drawing.Size GetPreferredSize (System.Drawing.Size Struct_Proposed)
{
return base.GetPreferredSize(Struct_Proposed);
}
protected void SetControlProperties (System.String String_Startup, System.Boolean Boolean_IconView, System.Drawing.Size Struct_IconSize, System.Drawing.Bitmap Object_Bitmap, System.Boolean Boolean_NullView, System.Boolean Boolean_NullType)
{
this.Control_Secondary = new RKSHARP2.Controls.RKQUESTIONWRITER.RKLAYOUT();
this.Control_Secondary.AutoSize = true;
this.Control_Secondary.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.Control_Secondary.BackColor = System.Drawing.Color.Transparent;
this.Control_Secondary.BackgroundImage = null;
this.Control_Secondary.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None;
this.Control_Secondary.CellBorderStyle = System.Windows.Forms.TableLayoutPanelCellBorderStyle.None;
this.Control_Secondary.ColumnCount = 4;
this.Control_Secondary.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100));
this.Control_Secondary.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.AutoSize, 0));
this.Control_Secondary.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.AutoSize, 0));
this.Control_Secondary.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100));
this.Control_Secondary.Dock = System.Windows.Forms.DockStyle.Left;
this.Control_Secondary.GrowStyle = System.Windows.Forms.TableLayoutPanelGrowStyle.FixedSize;
this.Control_Secondary.Margin = new System.Windows.Forms.Padding(0);
this.Control_Secondary.Padding = new System.Windows.Forms.Padding(0);
this.Control_Secondary.RowCount = 3;
this.Control_Secondary.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100));
this.Control_Secondary.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.AutoSize, 0));
this.Control_Secondary.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100));
this.Control_Secondary.Size = new System.Drawing.Size(0, 0);
this.Control_Secondary.TabIndex = 0;
this.Control_Secondary.TabStop = false;
this.Control_Secondary.Visible = true;
this.Control_IconView = new RKSHARP2.Controls.RKQUESTIONWRITER.RKBITMAP();
this.Control_IconView.AutoSize = false;
this.Control_IconView.BackColor = System.Drawing.Color.Transparent;
this.Control_IconView.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.Control_IconView.Cursor = System.Windows.Forms.Cursors.Default;
this.Control_IconView.Dock = System.Windows.Forms.DockStyle.Fill;
this.Control_IconView.Image = Object_Bitmap;
this.Control_IconView.Margin = new System.Windows.Forms.Padding(0);
this.Control_IconView.Padding = new System.Windows.Forms.Padding(0);
this.Control_IconView.Parent = this;
this.Control_IconView.Size = Struct_IconSize;
this.Control_IconView.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.Control_IconView.TabIndex = 0;
this.Control_IconView.TabStop = false;
this.Control_IconView.Visible = Boolean_IconView;
this.Control_IconView.VisibleChanged += new System.EventHandler(delegate(System.Object Object_Sender, System.EventArgs Object_Arguments){this.Control_IconView.Parent.Visible=this.IconView||this.NullView;});
this.Control_NullView = new RKSHARP2.Controls.RKQUESTIONWRITER.RKFLIPPER();
this.Control_NullView.AutoSize = true;
this.Control_NullView.BackColor = System.Drawing.Color.Transparent;
this.Control_NullView.Checked = true;
this.Control_NullView.Cursor = System.Windows.Forms.Cursors.Default;
this.Control_NullView.Dock = System.Windows.Forms.DockStyle.Fill;
this.Control_NullView.Enabled = !this.ReadOnly;
this.Control_NullView.Margin = new System.Windows.Forms.Padding(0);
this.Control_NullView.Padding = new System.Windows.Forms.Padding(0);
this.Control_NullView.Parent = this;
this.Control_NullView.Size = new System.Drawing.Size(0, 0);
this.Control_NullView.TabIndex = 0;
this.Control_NullView.TabStop = false;
this.Control_NullView.Text = "";
this.Control_NullView.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
this.Control_NullView.UseVisualStyleBackColor = true;
this.Control_NullView.Visible = Boolean_NullView;
this.Control_NullView.CheckedChanged += new System.EventHandler(delegate(System.Object Object_Sender, System.EventArgs Object_Arguments){this.ReadOnly=!this.Control_NullView.Checked;});
this.Control_NullView.VisibleChanged += new System.EventHandler(delegate(System.Object Object_Sender, System.EventArgs Object_Arguments){this.Control_NullView.Parent.Visible=this.NullView||this.IconView;});
this.Control_Secondary.SuspendLayout();
this.Control_Secondary.Controls.Add(RKSHARP2.Controls.RKQUESTIONWRITER.ConstructContainer(this.Control_IconView), 1, 1);
this.Control_Secondary.Controls.Add(RKSHARP2.Controls.RKQUESTIONWRITER.ConstructContainer(this.Control_NullView), 2, 1);
this.Control_Secondary.ResumeLayout();
this.Control_Secondary.PerformLayout();
this.Controls.Add(this.Control_Secondary);
}
protected static RKSHARP2.Controls.RKQUESTIONWRITER.RKLAYOUT ConstructContainer (System.Windows.Forms.Control Control_Temporary)
{
RKSHARP2.Controls.RKQUESTIONWRITER.RKLAYOUT Control_Container = new RKSHARP2.Controls.RKQUESTIONWRITER.RKLAYOUT();
Control_Container.SuspendLayout();
Control_Container.AutoSize = true;
Control_Container.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
Control_Container.BackColor = System.Drawing.Color.Transparent;
Control_Container.BackgroundImage = null;
Control_Container.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None;
Control_Container.CellBorderStyle = System.Windows.Forms.TableLayoutPanelCellBorderStyle.None;
Control_Container.ColumnCount = 3;
Control_Container.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100));
Control_Container.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.AutoSize, 0));
Control_Container.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100));
Control_Container.Dock = System.Windows.Forms.DockStyle.Fill;
Control_Container.GrowStyle = System.Windows.Forms.TableLayoutPanelGrowStyle.FixedSize;
Control_Container.Margin = new System.Windows.Forms.Padding(2);
Control_Container.Padding = new System.Windows.Forms.Padding(0);
Control_Container.RowCount = 3;
Control_Container.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100));
Control_Container.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.AutoSize, 0));
Control_Container.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100));
Control_Container.Size = new System.Drawing.Size(0, 0);
Control_Container.TabIndex = 0;
Control_Container.TabStop = false;
Control_Container.Visible = Control_Temporary.Visible;
Control_Container.Controls.Add(Control_Temporary, 1, 1);
Control_Container.ResumeLayout();
Control_Container.PerformLayout();
return Control_Container;
}
protected static void SetControlBuffer (System.IntPtr Pointer_Control, System.Int32 Integer_West, System.Int32 Integer_East)
{
RKSHARP2.Controls.RKWRITER.SetControlBuffer(Pointer_Control, Integer_West, Integer_East);
}
#pragma warning restore 1591
}

Related

How to set constraints in WinForm?

I created UserControl and put there a two GroupBox one at the top and one at the bottom... there is a screenshot
And then when I put this UserControl with my a views within to TabController I got such a result
So, as you see in the main form it looks like it is not enough space for all views within UserControl
Question is - is there a way to set that GroupBox at the top will take 50% of the height and GroupBox at the bottom will take also 50% of the height, such way this two GroupBox view will take 100% of the height each for 50%...
alternatively use TableLayoutPanel with two rows (each row gets 50% height)
private void InitializeComponent()
{
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.tableLayoutPanel1.SuspendLayout();
this.SuspendLayout();
//
// tableLayoutPanel1
//
this.tableLayoutPanel1.ColumnCount = 1;
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel1.Controls.Add(this.groupBox1, 0, 0);
this.tableLayoutPanel1.Controls.Add(this.groupBox2, 0, 2);
this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel1.Location = new System.Drawing.Point(3, 3);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
this.tableLayoutPanel1.RowCount = 3;
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 4F));
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel1.Size = new System.Drawing.Size(507, 408);
this.tableLayoutPanel1.TabIndex = 0;
//
// groupBox1
//
this.groupBox1.Dock = System.Windows.Forms.DockStyle.Fill;
this.groupBox1.Location = new System.Drawing.Point(3, 3);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(501, 196);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "groupBox1";
//
// groupBox2
//
this.groupBox2.Dock = System.Windows.Forms.DockStyle.Fill;
this.groupBox2.Location = new System.Drawing.Point(3, 209);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(501, 196);
this.groupBox2.TabIndex = 1;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "groupBox2";
//
// Form3
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(513, 414);
this.Controls.Add(this.tableLayoutPanel1);
this.Name = "Form3";
this.Padding = new System.Windows.Forms.Padding(3);
this.Text = "Form3";
this.tableLayoutPanel1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.GroupBox groupBox2;
you can use SplitContainer (IsSplitterFixed = true; will not allow to change proportions)
private void InitializeComponent()
{
this.splitContainer1 = new System.Windows.Forms.SplitContainer();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.groupBox2 = new System.Windows.Forms.GroupBox();
((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit();
this.splitContainer1.Panel1.SuspendLayout();
this.splitContainer1.Panel2.SuspendLayout();
this.splitContainer1.SuspendLayout();
this.SuspendLayout();
//
// splitContainer1
//
this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
this.splitContainer1.IsSplitterFixed = true;
this.splitContainer1.Location = new System.Drawing.Point(3, 3);
this.splitContainer1.Name = "splitContainer1";
this.splitContainer1.Orientation = System.Windows.Forms.Orientation.Horizontal;
//
// splitContainer1.Panel1
//
this.splitContainer1.Panel1.Controls.Add(this.groupBox1);
//
// splitContainer1.Panel2
//
this.splitContainer1.Panel2.Controls.Add(this.groupBox2);
this.splitContainer1.Size = new System.Drawing.Size(459, 395);
this.splitContainer1.SplitterDistance = 197;
this.splitContainer1.SplitterWidth = 1;
this.splitContainer1.TabIndex = 0;
//
// groupBox1
//
this.groupBox1.Dock = System.Windows.Forms.DockStyle.Fill;
this.groupBox1.Location = new System.Drawing.Point(0, 0);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(459, 197);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "groupBox1";
//
// groupBox2
//
this.groupBox2.Dock = System.Windows.Forms.DockStyle.Fill;
this.groupBox2.Location = new System.Drawing.Point(0, 0);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(459, 197);
this.groupBox2.TabIndex = 0;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "groupBox2";
//
// Form2
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(465, 401);
this.Controls.Add(this.splitContainer1);
this.Name = "Form2";
this.Padding = new System.Windows.Forms.Padding(3);
this.Text = "Form2";
this.splitContainer1.Panel1.ResumeLayout(false);
this.splitContainer1.Panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).EndInit();
this.splitContainer1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.SplitContainer splitContainer1;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.GroupBox groupBox2;

Grid.children.clear thread error xmpp wpf

I am calling a method that has a Grid.Children.Clear() functionality. When calling it from different methods it works well. But when I call my the method from an xmpp_onmessage method. I am experiencing an error. “The calling thread cannot access this object because a different thread owns it.”
Here is the method that containts Grid.Children.Clear()the :
private void ConstructChatView(Boolean isChat)
{
System.Uri resourceUri = new System.Uri("Public/Images/chat_green-textarea.png", UriKind.Relative);
StreamResourceInfo streamInfo = Application.GetResourceStream(resourceUri);
System.Uri resourceUri2 = new System.Uri("Public/Images/chat_green-textarea-tail.png", UriKind.Relative);
StreamResourceInfo streamInfo2 = Application.GetResourceStream(resourceUri2);
System.Uri resourceUri3 = new System.Uri("Public/Images/chat_blue-textarea.png", UriKind.Relative);
StreamResourceInfo streamInfo3 = Application.GetResourceStream(resourceUri3);
System.Uri resourceUri4 = new System.Uri("Public/Images/chat_blue-textarea-tail.png", UriKind.Relative);
StreamResourceInfo streamInfo4 = Application.GetResourceStream(resourceUri4);
BitmapFrame temp = BitmapFrame.Create(streamInfo.Stream);
var brush = new ImageBrush();
brush.ImageSource = temp;
BitmapFrame temp2 = BitmapFrame.Create(streamInfo2.Stream);
BitmapFrame temp3 = BitmapFrame.Create(streamInfo3.Stream);
var brush2 = new ImageBrush();
brush2.ImageSource = temp3;
BitmapFrame temp4 = BitmapFrame.Create(streamInfo4.Stream);
int ctr = 0;
chatGrid.Children.Clear();
if (isChat == true)
{
for (int i = 0; i < _messageView.Count; i++)
{
if ((!_messageView.ElementAt(i).Message.ToString().Trim().Equals("")))
{
RowDefinition chatGridRow1 = new RowDefinition();
RowDefinition chatGridRow2 = new RowDefinition();
RowDefinition chatGridRow3 = new RowDefinition();
chatGrid.RowDefinitions.Add(chatGridRow1);
chatGrid.RowDefinitions.Add(chatGridRow2);
chatGrid.RowDefinitions.Add(chatGridRow3);
if (_messageView.ElementAt(i).IsMe == true)
{
TextBlock Message = new TextBlock();
Message.Foreground = Brushes.White;
Message.Padding = new Thickness(10, 10, 10, 10);
Message.HorizontalAlignment = HorizontalAlignment.Right;
Message.Margin = new Thickness(0, 0, 5, 0);
Message.Background = brush2;
Message.TextWrapping = TextWrapping.Wrap;
Message.Text = _messageView.ElementAt(i).Message;
Grid.SetRow(Message, ctr);
Grid.SetColumn(Message, 0);
ctr++;
Image Bluetail = new Image();
Bluetail.Source = temp4;
Bluetail.HorizontalAlignment = HorizontalAlignment.Right;
Bluetail.Height = 10;
Bluetail.Width = 20;
Bluetail.Margin = new Thickness(0, -(0.7), 10, 0);
Grid.SetRow(Bluetail, ctr);
ctr++;
Label Sender = new Label();
Sender.Foreground = Brushes.White;
Sender.Margin = new Thickness(0, 0, 0, 10);
Sender.HorizontalAlignment = HorizontalAlignment.Right;
Sender.Content = "Sent By : " + _messageView.ElementAt(i).Name.ToString() + " " + _messageView.ElementAt(i).DateCreated.ToString();
Grid.SetRow(Sender, ctr);
Grid.SetColumn(Sender, 0);
ctr++;
chatGrid.Children.Add(Message);
chatGrid.Children.Add(Bluetail);
chatGrid.Children.Add(Sender);
}
else
{
TextBlock Message = new TextBlock();
Message.Foreground = Brushes.White;
Message.Padding = new Thickness(10, 10, 10, 10);
Message.HorizontalAlignment = HorizontalAlignment.Left;
Message.Margin = new Thickness(5, 0, 0, 0);
Message.Background = brush;
Message.TextWrapping = TextWrapping.Wrap;
Message.Text = _messageView.ElementAt(i).Message;
Grid.SetRow(Message, ctr);
Grid.SetColumn(Message, 0);
ctr++;
Image Greentail = new Image();
Greentail.Source = temp2;
Greentail.HorizontalAlignment = HorizontalAlignment.Left;
Greentail.Height = 10;
Greentail.Width = 20;
Greentail.Margin = new Thickness(10, -(0.7), 5, 0);
Grid.SetRow(Greentail, ctr);
ctr++;
Label Sender = new Label();
Sender.Foreground = Brushes.White;
Sender.Margin = new Thickness(0, 0, 0, 10);
Sender.HorizontalAlignment = HorizontalAlignment.Left;
Sender.Content = "Sent By : " + _messageView.ElementAt(i).Name.ToString() + " " + _messageView.ElementAt(i).DateCreated.ToString();
Grid.SetRow(Sender, ctr);
Grid.SetColumn(Sender, 0);
ctr++;
chatGrid.Children.Add(Message);
chatGrid.Children.Add(Greentail);
chatGrid.Children.Add(Sender);
}
}
}
}
else
{
for (int i = 0; i < _messageView.Count; i++)
{
if (_messageView.ElementAt(i).IsMe == true && (!_messageView.ElementAt(i).Message.ToString().Trim().Equals("")))
{
RowDefinition chatGridRow1 = new RowDefinition();
RowDefinition chatGridRow2 = new RowDefinition();
RowDefinition chatGridRow3 = new RowDefinition();
chatGrid.RowDefinitions.Add(chatGridRow1);
chatGrid.RowDefinitions.Add(chatGridRow2);
chatGrid.RowDefinitions.Add(chatGridRow3);
TextBlock Message = new TextBlock();
Message.Foreground = Brushes.White;
Message.Margin = new Thickness(0, 10, 300, 0);
Message.Padding = new Thickness(10, 10, 10, 10);
Message.HorizontalAlignment = HorizontalAlignment.Left;
Message.Background = brush;
Message.TextWrapping = TextWrapping.Wrap;
Message.Text = _messageView.ElementAt(i).Message;
Grid.SetRow(Message, ctr);
Grid.SetColumn(Message, 0);
ctr++;
Image Greentail = new Image();
Greentail.Source = temp2;
Greentail.HorizontalAlignment = HorizontalAlignment.Left;
Greentail.Height = 10;
Greentail.Width = 20;
Greentail.Margin = new Thickness(5, -(0.7), 0, 0);
Grid.SetRow(Greentail, ctr);
ctr++;
Label Sender = new Label();
Sender.Foreground = Brushes.White;
Sender.Margin = new Thickness(0, 0, 0, 10);
Sender.Content = "Sent By : " + _messageView.ElementAt(i).Name.ToString() + " " + _messageView.ElementAt(i).DateCreated.ToString();
Grid.SetRow(Sender, ctr);
Grid.SetColumn(Sender, 0);
ctr++;
chatGrid.Children.Add(Message);
chatGrid.Children.Add(Greentail);
chatGrid.Children.Add(Sender);
}
}
}
//for (int i = 0; i < _messageView.Count; i++)
//{
// if (_messageView.ElementAt(i).IsMe == true && (!_messageView.ElementAt(i).Message.ToString().Trim().Equals("")))
// {
// }
//}
ctr = 0;
scrollView.ScrollToEnd();
}
Any ideas? thanks
Most UI elements may only be modified in the UI thread. As your event handler is apparently invoked in a different thread, you have to use the Dispatcher to invoke your code in the UI thread.
private void ConstructChatView(Boolean isChat)
{
Dispatcher.Invoke((Action)(() => chatGrid.Children.Clear()));
}
EDIT: You may also pass more code to the Invoke call by using an anonymous method:
private void ConstructChatView(Boolean isChat)
{
Dispatcher.Invoke((Action)(() =>
{
// more code here
}));
}
Of course you may also put a bunch of code in another method and pass that to the Invoke call:
private void ConstructChatView(Boolean isChat)
{
Dispatcher.Invoke((Action)(() => ConstructChatViewInUI(isChat)));
}
private void ConstructChatViewInUI(Boolean isChat)
{
...
}

How to resize a stacklayoutpanel to fit its contents?

I have searched telerik's site for a while now and can not find any mention on how to resize a stacklayoupanel to fit its elements. There are properties that allow resizing to fit its elements; however, these properties are not working for me. I was wondering if there was anyone on here who has used this and can help me out. I have a list view that has listViewVisualItems that do not fit their contents. Rather the contents "leak" out of the visual items below and bleed into the next one.
Here is my custom item class.
public class ChargePlotListViewItem : SimpleListViewVisualItem
{
private LightVisualElement imageElement;
private LightVisualElement titleElement;
private LightVisualElement bioElement;
private StackLayoutPanel stackLayout;
protected override void CreateChildElements()
{
base.CreateChildElements();
stackLayout = new StackLayoutPanel();
stackLayout.Orientation = System.Windows.Forms.Orientation.Vertical;
//stackLayout.AutoSize = true; These do not work
//stackLayout.AutoSizeMode = RadAutoSizeMode.WrapAroundChildren;
imageElement = new LightVisualElement();
imageElement.DrawText = false;
imageElement.ImageLayout = System.Windows.Forms.ImageLayout.Zoom;
//imageElement.StretchVertically = false;
imageElement.Margin = new System.Windows.Forms.Padding(1, 1, 1, 2);
imageElement.ShouldHandleMouseInput = false;
imageElement.NotifyParentOnMouseInput = true;
imageElement.AutoSizeMode = RadAutoSizeMode.FitToAvailableSize;
//stackLayout.Children.Add(imageElement);
titleElement = new LightVisualElement();
titleElement.TextAlignment = ContentAlignment.TopCenter;
titleElement.Margin = new Padding(2, 1, 1, 2);
titleElement.Font = new System.Drawing.Font("Segoe UI", 8, FontStyle.Italic, GraphicsUnit.Point);
titleElement.ShouldHandleMouseInput = false;
titleElement.NotifyParentOnMouseInput = true;
stackLayout.Children.Add(titleElement);
bioElement = new LightVisualElement();
bioElement.TextAlignment = ContentAlignment.BottomLeft;
bioElement.ShouldHandleMouseInput = false;
bioElement.NotifyParentOnMouseInput = true;
bioElement.Margin = new Padding(2, 1, 1, 2);
bioElement.Font = new System.Drawing.Font("Segoe UI", 9, FontStyle.Regular, GraphicsUnit.Point);
bioElement.ForeColor = Color.FromArgb(255, 114, 118, 125);
stackLayout.Children.Add(bioElement);
this.Children.Add(stackLayout);
//this.stackLayout.Measure(new System.Drawing.SizeF((float)stackLayout.Size.Width, (float)20));
this.Padding = new Padding(1, 2, 1, 2);
this.Shape = new RoundRectShape(3);
this.BorderColor = Color.Black;
this.BorderGradientStyle = GradientStyles.Solid;
this.DrawBorder = true;
this.DrawFill = true;
this.BackColor = Color.Azure;
this.GradientStyle = GradientStyles.Solid;
}
protected override void SynchronizeProperties()
{
base.SynchronizeProperties();
frmBingMaps.CriminalPlotObject plotObject = this.Data.Value as frmBingMaps.CriminalPlotObject;
if (plotObject != null)
{
try
{
this.imageElement.Image = Crime_Information_System.Properties.Resources
.bullet_blue;
}
catch
{
}
//building the title for the element depending on which names are on record
StringBuilder NameBuilder = new StringBuilder();
if (plotObject.Data.FirstName != null | plotObject.Data.FirstName != string.Empty)
NameBuilder.Append(plotObject.Data.FirstName + " ");
if (plotObject.Data.LastName != null | plotObject.Data.LastName != string.Empty)
NameBuilder.Append(plotObject.Data.LastName + " ");
//NameBuilder.Append(" Charge: " + gangBanger.Incidents[0].Charges[0].ChargeDescription);
this.titleElement.Text = NameBuilder.ToString();
StringBuilder BioBuilder = new StringBuilder();
//this.radDesktopAlert1.ContentText = "<html><b>" + CentralDataStore.AllUsers.Find(P => P.intUserID
// == BLAH.SenderID).strFirstName + " " + CentralDataStore.AllUsers.Find(P => P.intUserID ==
// BLAH.SenderID).strLastName + "</b><br>" + BLAH.Subject;
BioBuilder.Append("<html>");
BioBuilder.Append("<b>Incident ID</b>: " + plotObject.Data.Incidents.Find(
P => P.IncidentID == plotObject.CaseID).IncidentID.ToString());
BioBuilder.Append("<br>");
BioBuilder.Append("<b>Date</b>: " + plotObject.Data.Incidents.Find(
P => P.IncidentID == plotObject.CaseID).DateOfIncident.ToShortDateString());
BioBuilder.Append("<br>");
BioBuilder.Append(plotObject.Data.Incidents.Find(P => P.IncidentID == plotObject
.CaseID).Description);
BioBuilder.Append("<br>");
//BioBuilder.Append("\r\n");
BioBuilder.Append("<b>Location</b>: ");
BioBuilder.Append(plotObject.Data.Incidents.Find(P => P.IncidentID ==
plotObject.CaseID).Location);
BioBuilder.Append("<br>");
//BioBuilder.Append("\r\n");
BioBuilder.Append(string.Format("<b>Charges</b>: "));
foreach (Charge c in plotObject.Data.Incidents.Find(P => P.IncidentID == plotObject.CaseID
).Charges)
{
BioBuilder.Append(c.ChargeDescription + ", ");
}
BioBuilder.Remove(BioBuilder.Length - 2,2);
//BioBuilder.Append("
bioElement.Text = BioBuilder.ToString();
this.Text = ""; //here to erase the system.crimesysteminformation.plot blah object name
}
}
protected override Type ThemeEffectiveType
{
get
{
return typeof(IconListViewVisualItem);
}
}
protected override SizeF MeasureOverride(SizeF availableSize)
{
SizeF measuredSize = base.MeasureOverride(availableSize);
this.stackLayout.Measure(measuredSize);
return measuredSize;
}
protected override SizeF ArrangeOverride(SizeF finalSize)
{
base.ArrangeOverride(finalSize);
this.stackLayout.Arrange(new RectangleF(PointF.Empty, finalSize));
return finalSize;
}
To overcome this behavior, please consider allowing the items take their desired size by setting the following property:
radListView1.AllowArbitraryItemHeight = true;
For your convenience, here is a simplified version of your code in action:
void radListView1_VisualItemCreating(object sender, ListViewVisualItemCreatingEventArgs e)
{
e.VisualItem = new ChargePlotListViewItem();
}
public class ChargePlotListViewItem : SimpleListViewVisualItem
{
private LightVisualElement imageElement;
private LightVisualElement titleElement;
private LightVisualElement bioElement;
private StackLayoutPanel stackLayout;
protected override void CreateChildElements()
{
base.CreateChildElements();
stackLayout = new StackLayoutPanel();
stackLayout.Orientation = System.Windows.Forms.Orientation.Vertical;
imageElement = new LightVisualElement();
imageElement.DrawText = false;
imageElement.ImageLayout = System.Windows.Forms.ImageLayout.Center;
imageElement.ShouldHandleMouseInput = false;
imageElement.NotifyParentOnMouseInput = true;
stackLayout.Children.Add(imageElement);
titleElement = new LightVisualElement();
titleElement.TextAlignment = ContentAlignment.TopCenter;
titleElement.Font = new System.Drawing.Font("Segoe UI", 8, FontStyle.Italic, GraphicsUnit.Point);
titleElement.ShouldHandleMouseInput = false;
titleElement.NotifyParentOnMouseInput = true;
stackLayout.Children.Add(titleElement);
bioElement = new LightVisualElement();
bioElement.TextAlignment = ContentAlignment.BottomLeft;
bioElement.ShouldHandleMouseInput = false;
bioElement.NotifyParentOnMouseInput = true;
bioElement.Margin = new Padding(2, 1, 1, 2);
bioElement.Font = new System.Drawing.Font("Segoe UI", 9, FontStyle.Regular, GraphicsUnit.Point);
bioElement.ForeColor = Color.FromArgb(255, 114, 118, 125);
stackLayout.Children.Add(bioElement);
this.Children.Add(stackLayout);
}
protected override void SynchronizeProperties()
{
base.SynchronizeProperties();
DataRowView rowView = this.Data.DataBoundItem as DataRowView;
imageElement.Image = (Image)rowView.Row["Image"];
titleElement.Text = rowView.Row["Title"].ToString();
bioElement.Text = rowView.Row["Bio"].ToString();
this.Text = ""; //here to erase the system.crimesysteminformation.plot blah object name
}
protected override Type ThemeEffectiveType
{
get
{
return typeof(IconListViewVisualItem);
}
}
}

Program to generate Tables, trouble using Events

I am doing a program in C# for kids with which kids can test their knowledge of Multiplication tables.
I cannot get the value of 'i' in the Result_Leave() function to track which value of the text box array is incorrect.
For Example:
5 X 1 = [ ] <---- an array of textboxes with name Result[i]"
the user enters the value of 5*1 in the text box and my program instantly checks if the entered value is correct or not, using the "Leave" event for the text box.
I have used an array of text boxes...
So I cannot track which Result[i] contains the incorrect value...
I have fired the function "Result_Leave" for each of the text boxes "Result[i]"
Here is the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Tables
{
public partial class FormMain : Form
{
private System.Windows.Forms.Label[] labelNumber;
private System.Windows.Forms.Label[] labelCross;
private System.Windows.Forms.Label[] labelTableOf;
private System.Windows.Forms.Label[] labelEquals;
/*"Result" is an array of textboxes which takes the result of the multiplication from the user*/
private System.Windows.Forms.TextBox[] Result; //declaration
public FormMain()
{
InitializeComponent();
WindowState = FormWindowState.Maximized;
buttonCheckAnswers.Enabled = false;
}
private void buttonGo_Click(object sender, EventArgs e)
{
if (textBoxInput.Text == "")
{
errorProvider1.SetError(textBoxInput, "Hey! Enter a number please");
}
else
{
textBoxInput.Enabled = false;
buttonCheckAnswers.Enabled = true;
labelNumber = new System.Windows.Forms.Label[10];
labelCross = new System.Windows.Forms.Label[10];
labelTableOf = new System.Windows.Forms.Label[10];
labelEquals = new System.Windows.Forms.Label[10];
Result = new System.Windows.Forms.TextBox[10];
for (int i = 0; i < 10; i++)
{
// this snippet generates code for adding controls at runtime viz. textboxes and labels
labelNumber[i] = new Label();
this.labelNumber[i].AutoSize = true;
this.labelNumber[i].Location = new System.Drawing.Point(200, 163 + 55 * i);
this.labelNumber[i].Name = "labelNumber";
this.labelNumber[i].Size = new System.Drawing.Size(35, 13);
this.labelNumber[i].Text = (i + 1).ToString();
this.labelNumber[i].Font = new System.Drawing.Font("Comic Sans MS", 17F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.labelNumber[i].ForeColor = System.Drawing.Color.Khaki;
this.Controls.AddRange(new System.Windows.Forms.Control[] { labelNumber[i] });
labelCross[i] = new Label();
this.labelCross[i].AutoSize = true;
this.labelCross[i].Location = new System.Drawing.Point(150, 163 + 55 * i);
this.labelCross[i].Name = "labelCross";
this.labelCross[i].Size = new System.Drawing.Size(35, 13);
this.labelCross[i].Text = "X";
this.labelCross[i].Font = new System.Drawing.Font("Comic Sans MS", 17F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.labelCross[i].ForeColor = System.Drawing.Color.Khaki;
this.Controls.AddRange(new System.Windows.Forms.Control[] { labelCross[i] });
labelTableOf[i] = new Label();
this.labelTableOf[i].AutoSize = true;
this.labelTableOf[i].Location = new System.Drawing.Point(100, 163 + 55 * i);
this.labelTableOf[i].Name = "labelTableOf";
this.labelTableOf[i].Size = new System.Drawing.Size(35, 13);
this.labelTableOf[i].Text = textBoxInput.Text;
this.labelTableOf[i].Font = new System.Drawing.Font("Comic Sans MS", 17F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.labelTableOf[i].ForeColor = System.Drawing.Color.Khaki;
this.Controls.AddRange(new System.Windows.Forms.Control[] { labelTableOf[i] });
labelEquals[i] = new Label();
this.labelEquals[i].AutoSize = true;
this.labelEquals[i].Location = new System.Drawing.Point(250, 163 + 55 * i);
this.labelEquals[i].Name = "labelTableOf";
this.labelEquals[i].Size = new System.Drawing.Size(35, 13);
this.labelEquals[i].Text = "=";
this.labelEquals[i].Font = new System.Drawing.Font("Comic Sans MS", 17F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.labelEquals[i].ForeColor = System.Drawing.Color.Khaki;
this.Controls.AddRange(new System.Windows.Forms.Control[] { labelEquals[i] });
/*"Result" is an array of textboxes which takes the result of the multiplication from the user*/
Result[i] = new TextBox();
this.Result[i].BackColor = System.Drawing.Color.BlueViolet;
this.Result[i].Font = new System.Drawing.Font("Comic Sans MS", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Result[i].ForeColor = System.Drawing.SystemColors.Info;
this.Result[i].Location = new System.Drawing.Point(300, 163 + 55 * i);
this.Result[i].Name = "Result" + i;
this.Result[i].Size = new System.Drawing.Size(57, 37);
this.Result[i].TabIndex = i;
/*this is where the problem arises...*/
this.Result[i].Leave += new System.EventHandler(this.Result_Leave);// how do I send the value of 'i' to Result_Leave() function
/*Note - Result_Leave() is FIRED when the cursor moves away from the "Result" textbox*/
this.Controls.AddRange(new System.Windows.Forms.Control[] { Result[i] });
}
}
}
private void textBoxInput_TextChanged(object sender, EventArgs e)
{
errorProvider1.Clear();
}
private void radioButtonInstantChecking_CheckedChanged(object sender, EventArgs e)
{
if (radioButtonCheckAtLast.Checked == true && textBoxInput.Text!="")
{
buttonCheckAnswers.Enabled = true;
}
else buttonCheckAnswers.Enabled = false;
}
private void Result_Leave(object sender, EventArgs e)
{
/*Code for checking multiplication goes here*/
/*If multiplication result entered by the user is
*correct change the background colour of the corresponding textbox "Result[i] to GREEN else BLUE"
*as in buttonCheckAnswers_Click() function...
*/
}
private void textBoxInput_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
{
e.Handled = true;
}
// only allow one decimal point
if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -2)
e.Handled = true;
}
private void buttonCheckAnswers_Click(object sender, EventArgs e)
{
int score=0;
bool flag=false;
for (int i = 0; i < 10; i++)
{
if (Result[i].Text == "")
{
flag = true;
break;
}
else if ((Convert.ToInt32(Result[i].Text)) != ((Convert.ToInt32(labelNumber[i].Text) * (Convert.ToInt32(labelTableOf[i].Text)))))
{
Result[i].BackColor = System.Drawing.Color.Red;
}
else
{
Result[i].BackColor = System.Drawing.Color.Green;
score += 1;
}
}
if (score == 10)
labelComments.Text = "Well done kid! Full Marks!\nYou know your table of\n"+textBoxInput.Text+" very well"+"\nScore = "+score;
else if(flag)
labelComments.Text = "Oops! \nComplete your table kid!";
else
labelComments.Text = "Oops! \nThere are errors. \nPlease revise your tables!" + "\nYour score is : " + score;
}
}
}
One quick-and-dirty way to do this is to set a value in each TextBox's Tag property. In the for loop inside buttonGo_Click, you could set Result[i].Tag = i;, then in Result_Leave you could do:
int number = (int)((sender as TextBox).Tag);

Control for tags with auto-completion in Winforms?

I am seeking a WinForm control that would provide an autocomplete behavior for multiple space-separated - exactly ala del.icio.us (or stackoverflow.com for that matter).
Does anyone knows how to do that within a .NET 2.0 WinForm application?
ComboBox can autocomplete, but only one word at a time.
If you want to have each word separately autocompleted, you have to write your own.
I already did, hope it's not too long. It's not 100% exactly what you want, this was used for autocompleting in email client when typing in email adress.
/// <summary>
/// Extended TextBox with smart auto-completion
/// </summary>
public class TextBoxAC: TextBox
{
private List<string> completions = new List<string>();
private List<string> completionsLow = new List<string>();
private bool autocompleting = false;
private bool acDisabled = true;
private List<string> possibleCompletions = new List<string>();
private int currentCompletion = 0;
/// <summary>
/// Default constructor
/// </summary>
public TextBoxAC()
{
this.TextChanged += new EventHandler(TextBoxAC_TextChanged);
this.KeyPress += new KeyPressEventHandler(TextBoxAC_KeyPress);
this.KeyDown += new KeyEventHandler(TextBoxAC_KeyDown);
this.TabStop = true;
}
/// <summary>
/// Sets autocompletion data, list of possible strings
/// </summary>
/// <param name="words">Completion words</param>
/// <param name="wordsLow">Completion words in lowerCase</param>
public void SetAutoCompletion(List<string> words, List<string> wordsLow)
{
if (words == null || words.Count < 1) { return; }
this.completions = words;
this.completionsLow = wordsLow;
this.TabStop = false;
}
private void TextBoxAC_TextChanged(object sender, EventArgs e)
{
if (this.autocompleting || this.acDisabled) { return; }
string text = this.Text;
if (text.Length != this.SelectionStart) { return; }
int pos = this.SelectionStart;
string userPrefix = text.Substring(0, pos);
int commaPos = userPrefix.LastIndexOf(",");
if (commaPos == -1)
{
userPrefix = userPrefix.ToLower();
this.possibleCompletions.Clear();
int n = 0;
foreach (string s in this.completionsLow)
{
if (s.StartsWith(userPrefix))
{
this.possibleCompletions.Add(this.completions[n]);
}
n++;
}
if (this.possibleCompletions.Count < 1) { return; }
this.autocompleting = true;
this.Text = this.possibleCompletions[0];
this.autocompleting = false;
this.SelectionStart = pos;
this.SelectionLength = this.Text.Length - pos;
}
else
{
string curUs = userPrefix.Substring(commaPos + 1);
if (curUs.Trim().Length < 1) { return; }
string trimmed;
curUs = this.trimOut(curUs, out trimmed);
curUs = curUs.ToLower();
string oldUs = userPrefix.Substring(0, commaPos + 1);
this.possibleCompletions.Clear();
int n = 0;
foreach (string s in this.completionsLow)
{
if (s.StartsWith(curUs))
{
this.possibleCompletions.Add(this.completions[n]);
}
n++;
}
if (this.possibleCompletions.Count < 1) { return; }
this.autocompleting = true;
this.Text = oldUs + trimmed + this.possibleCompletions[0];
this.autocompleting = false;
this.SelectionStart = pos;
this.SelectionLength = this.Text.Length - pos + trimmed.Length;
}
this.currentCompletion = 0;
}
private void TextBoxAC_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Back || e.KeyCode == Keys.Delete)
{
this.acDisabled = true;
}
if (e.KeyCode == Keys.Up || e.KeyCode == Keys.Down)
{
if ((this.acDisabled) || (this.possibleCompletions.Count < 1))
{
return;
}
e.Handled = true;
if (this.possibleCompletions.Count < 2) { return; }
switch (e.KeyCode)
{
case Keys.Up:
this.currentCompletion--;
if (this.currentCompletion < 0)
{
this.currentCompletion = this.possibleCompletions.Count - 1;
}
break;
case Keys.Down:
this.currentCompletion++;
if (this.currentCompletion >= this.possibleCompletions.Count)
{
this.currentCompletion = 0;
}
break;
}
int pos = this.SelectionStart;
string userPrefix = this.Text.Substring(0, pos);
int commaPos = userPrefix.LastIndexOf(",");
if (commaPos == -1)
{
pos--;
userPrefix = this.Text.Substring(0, pos);
this.autocompleting = true;
this.Text = userPrefix + this.possibleCompletions[this.currentCompletion].Substring(userPrefix.Length);
this.autocompleting = false;
this.SelectionStart = pos + 1;
this.SelectionLength = this.Text.Length - pos;
}
else
{
string curUs = userPrefix.Substring(commaPos + 1);
if (curUs.Trim().Length < 1) { return; }
string trimmed;
curUs = this.trimOut(curUs, out trimmed);
curUs = curUs.ToLower();
string oldUs = userPrefix.Substring(0, commaPos + 1);
this.autocompleting = true;
this.Text = oldUs + trimmed + this.possibleCompletions[this.currentCompletion];
this.autocompleting = false;
this.SelectionStart = pos;
this.SelectionLength = this.Text.Length - pos + trimmed.Length;
}
}
}
private void TextBoxAC_KeyPress(object sender, KeyPressEventArgs e)
{
if (!Char.IsControl(e.KeyChar)) { this.acDisabled = false; }
}
private string trimOut(string toTrim, out string trim)
{
string ret = toTrim.TrimStart();
int pos = toTrim.IndexOf(ret);
trim = toTrim.Substring(0, pos);
return ret;
}
}

Resources