Reputation: 1885
I'm making a custom control textbox that has a Cue
(filler text) and CueColor
(filler text color) properties. I created an Enter
and Leave
event inside the textbox to regulate the Cue. When I tried applying it, however, it crashes my IDE (Visual Studio 2015, if this helps).
I've read a few posts with similar questions: Winforms user controls custom events
Although I'm not quite sure if my problem has the same solution. How do I make it work? Here is my code for clarity:
class CueTextBox : TextBox
{
public string Cue
{
get { return Cue; }
set { Cue = value;}
}
public Color CueColor
{
get { return CueColor; }
set { CueColor = value; }
}
private void CueTextBox_Enter(object sender, EventArgs e)
{
TextBox t = sender as TextBox;
if (t.ForeColor == this.CueColor)
{
t.Text = "";
t.ForeColor = this.ForeColor;
}
}
private void CueTextBox_Leave(object sender, EventArgs e)
{
TextBox t = sender as TextBox;
if (t.Text.Trim().Length == 0)
{
t.Text = Cue;
t.ForeColor = this.CueColor;
}
}
}
Upvotes: 0
Views: 591
Reputation: 11801
The only thing that I see in your code is that the property definitions are recursively calling themselves and this will cause a stack overflow when adding the control to the design surface.
public string Cue
{
get { return Cue; }
set { Cue = value;}
}
Either define a backing field or use auto-implemented properties.
private string cue = String.Empty;
public string Cue
{
get { return cue; }
set { cue = value; }
}
or
public string Cue { get; set; }
Your question implied adding event handlers caused the issue. This can be a problem for custom controls at times. There is the Control.DesignMode property that is meant to allow conditional execution of code. However, it does not operate in the constructor. You need to do a bit of a hack to determine if the IDE is active.
This property can be used for development in Visual Studio as an alternative to DesignMode
.
private bool InDesignMode
{
get
{
return (System.ComponentModel.LicenseManager.UsageMode == System.ComponentModel.LicenseUsageMode.Designtime) ||
base.DesignMode ||
(System.Diagnostics.Process.GetCurrentProcess().ProcessName == "devenv");
}
}
In solution development of custom controls is an exercise in self abuse. You are better of to go to Project Properties->Debug Tab and set the "Start Action" to "Start External Program" with "devenv.exe" as the program. This will start a new instance of VS when you "run" the debugger. When you add a control to the design surface of the new VS instance, you can debug your control's code. Break points will be hit and exceptions displayed.
Upvotes: 1