Introduction
I wanted to localize my Windows Forms programmatically, and had this problem for several months, and I couldn't find a possible solution in any of the forums. By simply creating a Visual Studio add-in, you can easily make your Windows forms localizable. And here, I publish the basic code for doing that, and this program only identifies Windows forms in the "Forms" directory in my folder structure. Thus, you may have to change the directory name where your forms exist.
Using the code
- First, you have to create a Visual Studio Extensibility Project using VS2005
.
You can get an idea of how to create an add-in here: Creating a tool window add-in with Visual Studio 2005.
- You have to follow the Wizard as it is for a basic add-in like the above, and you have to check the first check box in order to create a menu item in your Visual Studio Tools menu.
- After creating your add-in project using the Wizard, you can add the following code in the following method in the
Connect
class:
public void Exec(string commandName,
vsCommandExecOption executeOption, ref object varIn,
ref object varOut, ref bool handled)
{
handled = false;
if (executeOption == vsCommandExecOption.vsCommandExecOptionDoDefault)
{
if(commandName == "MyAddin1.Connect.MyAddin1")
{
handled = true;
try
{
foreach (
EnvDTE.Project project in
_applicationObject.DTE.Solution.Projects)
{
foreach (EnvDTE.ProjectItem item in project.ProjectItems)
{
if (item.Name == "Forms")
{
EnvDTE.ProjectItems forms = item.ProjectItems;
foreach (EnvDTE.ProjectItem appForm in forms)
{
EnvDTE.Window appFormWindow = appForm.Open(
EnvDTE.Constants.vsext_vk_Designer);
if (appFormWindow != null)
{
appFormWindow.Visible = true;
IDesignerHost designerHost =
appFormWindow.Object as IDesignerHost;
TypeDescriptionProvider p =
TypeDescriptor.GetProvider(
designerHost.RootComponent);
ICustomTypeDescriptor t=
p.GetExtendedTypeDescriptor(
designerHost.RootComponent);
PropertyDescriptorCollection propCollection =
t.GetProperties();
PropertyDescriptor propDesc =
propCollection["Localizable"]
as PropertyDescriptor;
if (propDesc != null)
{
propDesc.SetValue(designerHost.RootComponent,
true);
}
appFormWindow.Close(
EnvDTE.vsSaveChanges.vsSaveChangesYes);
}
}
}
}
}
}
catch (Exception e)
{
throw e;
}
return;
}
}
}
- Build your add-in.There you go! Now, open a Visual Studio project and find the newly created menu item under the Tools menu.
- If you have your forms under the “Forms” folder in your project, you will see your forms have got localized automatically.
- You will see some flickering during the execution because I am opening those forms in the Designer programmatically, so don’t worry about it.
Points of interest
Just thought of sharing this. Hope this will help for larger projects when you require to localize all your forms in projects.
I've been working as a Software Engineer for three years and really interested in Computer Science research activities.