I have a function in my WinForm application to translate all the Form controls from English to another language.
public static void SetControls(Control control)
{
try
{
foreach (Control c in control.Controls)
{
var TextProperty = c.GetType().GetProperty("Text");
if (TextProperty != null)
{
string currentValue = (string)TextProperty.GetValue(c);
if (!String.IsNullOrEmpty(currentValue))
{
if (m_dictionary != null && m_dictionary.ContainsKey(currentValue))
{
string translatedValue = m_dictionary[currentValue];
if (!String.IsNullOrEmpty(translatedValue))
{
TextProperty.SetValue(c, translatedValue, null);
}
}
}
}
SetControls(c);
}
}
catch (Exception ex)
{
// error handler
}
}
The function loops recursively through all the controls and changes its Text property.
m_dictionary
is just a dictionary that contains original and translated text:
private static Dictionary<string, string> m_dictionary;
If I call the function from the form constructor:
public MainForm()
{
InitializeComponent();
SetControls(this);
}
that works fine. But if I call the function from a button handler, when the form is up I get crash error:
Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
If I disable the form while changing that works better but anyway failed in 20% of tries:
this.Enabled = false;
SetControls(this);
this.Enabled = true;
What could it be and how can I solve this strange error?