Change input language doesn't work - c#

I need to change the keyboard input language and set it to English from C# (I need an .exe for do it), the problem is that the program works in Visual Studio, but when I launch the .exe it doesn't change the keyboard.
I have this in the main method on a winforms app
static void Main(){
InputLanguage englishLayout = GetInputLanguageByName("english");
if (englishLayout!=null) {
InputLanguage.CurrentInputLanguage = englishLayout;
}
else
{
Console.WriteLine("nulo.");
}
This method searches the installed languages
public static InputLanguage GetInputLanguageByName(string inputName){
foreach (InputLanguage lang in InputLanguage.InstalledInputLanguages){
Console.WriteLine(lang.LayoutName);
if (lang.Culture.EnglishName.ToLower().StartsWith(inputName))
return lang;
}
return null;
}
Just need that from the application (do not need forms, just change the keyboard language), but when I launch the .exe outside Visual Studio it doesn't work.

Related

How to set C# application icon on Control Panel for Visual Studio 2015

This is a cosmetic issue but my application has a default icon on the control panel. Many other applications have custom icons.
My application does have custom icons for the menu and task bar.
How can the icon displayed on the Control Panel be changed using Visual Studio 2015 or later?
Update:
There has been a change in how Visual Studio creates installers. I'm not sure when it occurred, but 2015 definitely does not have a "deployment project". The majority of the hits on Google suggest going to the deployment project properties which does not exist under VS 2015 apps.
This was why I included the tag for visual-studio-2015. Sorry, not to have mentioned that in the original question. It would have been good information.
Using the registry is a possibility but the registry path mentioned, HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall, does not exist. It does sound kludgy to have the application check it's own icon in the registry all the time. It sounds like an installer function to me.
A post on the Microsoft Developer Network provided an answer. It also modifies the registry. I enhanced it by removing hard-coded values for the application name and the icon file.
// These references are needed:
// using System.Reflection;
// using System.Deployment.Application;
// using System.IO;
// using Microsoft.Win32;
private static void SetAddRemoveProgramsIcon(string iconName)
{
// only run if deployed
if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed && ApplicationDeployment.CurrentDeployment.IsFirstRun)
{
try
{
string assemblyTitle="";
object[] titleAttributes = Assembly.GetEntryAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), true);
if (titleAttributes.Length > 0 && titleAttributes[0] is AssemblyTitleAttribute)
{
assemblyTitle = (titleAttributes[0] as AssemblyTitleAttribute).Title;
}
string iconSourcePath = Path.Combine(System.Windows.Forms.Application.StartupPath, iconName);
if (!File.Exists(iconSourcePath))
{
return;
}
RegistryKey myUninstallKey = Registry.CurrentUser.OpenSubKey(#"Software\Microsoft\Windows\CurrentVersion\Uninstall");
string[] mySubKeyNames = myUninstallKey.GetSubKeyNames();
for (int i = 0; i < mySubKeyNames.Length; i++)
{
RegistryKey myKey = myUninstallKey.OpenSubKey(mySubKeyNames[i], true);
object myValue = myKey.GetValue("DisplayName");
if (myValue != null && myValue.ToString() == assemblyTitle)
{
myKey.SetValue("DisplayIcon", iconSourcePath);
break;
}
}
}
catch (Exception) { }
}
return;
}
The original article by Robin Shahan is here: RobinDotNet
For WPF application we need to replace the following code
string iconSourcePath = Path.Combine(System.Windows.Forms.Application.StartupPath, iconName);
Replace with below code
string iconSourcePath = Path.Combine(System.Environment.GetFolderPath(Environment.SpecialFolder.Startup), "TestIcon.ico");
I know you want 2015 but others may be looking for this in newer versions, like I was.
In Visual Studio 2019 Community we can go to the properties panel for the main setup project and the top property is AddRemoveProgramsIcon.
I have just come through this case today. I know it is old but will be useful for new seekers. To expose icon in Control Panel do the following:
Make a folder in [solution Folder][Project Folder]\bin\debug\images
Copy your icon in the new folder
In Set Up project always refer to the icon in the new created folder.
Solved my problem easily

Programmatically reset VisualStudio shortcuts

There are two related questions about resetting VisualStudio keyboard scheme and importing VisualStudio settings. However, this doesn't seem to play nice all together.
I have two settings files containing shortcuts:
<!-- IntelliJ.vssettings -->
<ShortcutsScheme>Visual C# 2005</ShortcutsScheme>
<UserShortcuts>
<Shortcut Command="ReSharper.ReSharper_GotoNextHighlight" Scope="Global">F12</Shortcut>
</UserShortcuts>
<!-- ReSharper.vssettings -->
<ShortcutsScheme>Visual C# 2005</ShortcutsScheme>
<UserShortcuts>
<!-- Implicitly has F12 assigned to Edit.GoToDefinition -->
</UserShortcuts>
As you see ReSharper.vssettings doesn't really have the F12 shortcut assigned, since it is the default for VisualStudio. Importing that file, will not reapply the ShortcutsScheme, which is Visual Studio C# 2005 in both cases. This in turn results in the fact, that F12 keeps executing the GotoNextHighlight command. Same problem when just using the import dialog.
Using DTE as follows to reset the keyboard scheme also doesn't work:
var property = dte.Properties["Environment", "Keyboard"];
property.Item("SchemeName").Value = "(Default)";
Exporting the default settings doesn't work for the same reason. As shown here no shortcuts are exported.
Question therefore: How can I reset the VisualStudio keyboard scheme programmatically using DTE?
What I actually need is the command to trigger the Reset button in Options | Environment | Keyboard dialog.
You can remove specific key bindings as per:
Visual Studio key bindings configuration file
Unfortunately I dont have both IntelliJ and ReSharper to test if it works. If it does it'd be nice to do this using DTE however this solution is beyond the scope of DTE and would be trivial using System.IO.File.
UPDATE:
Question: How can I reset the VisualStudio keyboard scheme programmatically using DTE? What I actually need is the command to trigger the Reset button in Options | Environment | Keyboard dialog.
Unfortunately you cannot do it (AFAIK) because resetting the Keyboard Shortcuts is beyond the scope of DTE.
If you setup a VS AddIn Project called "ResetKeyBoard" and put a break point on the Exec method you will see DTE doesnt catch any Visual Studio events firing when you're inside the Tools Options window, they simply aren't exposed through the DTE Object model:
public void Exec(string commandName, vsCommandExecOption executeOption, ref object varIn, ref object varOut, ref bool handled)
This can also be demonstrated by Recording a Macro, the recorded commands only go so deep as to open the Option Dialog (no matter what settings you change inside):
Public Module RecordingModule
Sub TemporaryMacro()
DTE.ExecuteCommand("Tools.Options")
End Sub
End Module
I did learn how to open the Keyboard tab of the Options window directly but since its a Modal Dialog you cant even use SendKeys to press the Reset button:
public void Exec(string commandName, vsCommandExecOption executeOption, ref object varIn, ref object varOut, ref bool handled)
{
handled = false;
if(executeOption == vsCommandExecOption.vsCommandExecOptionDoDefault)
{
if(commandName == "ResetKeyBoard.Connect.ResetKeyBoard")
{
_applicationObject.ExecuteCommand("Tools.Options", "BAFF6A1A-0CF2-11D1-8C8D-0000F87570EE");
System.Windows.Forms.SendKeys.Send("%e");
System.Windows.Forms.SendKeys.Send("{ENTER}");
The last DTE option I tried (without luck) is using Commands.Raise, again you cant get deeper than opening Tools Options or at least if you can its undocumented.
public void Exec(string commandName, vsCommandExecOption executeOption, ref object varIn, ref object varOut, ref bool handled)
{
handled = false;
if(executeOption == vsCommandExecOption.vsCommandExecOptionDoDefault)
{
if(commandName == "ResetKeyBoard.Connect.ResetKeyBoard")
{
Commands cmds = _applicationObject.Commands;
Command cmdobj = cmds.Item("Tools.Options");
object customIn = null;
object customOut = null;
_applicationObject.Commands.Raise(cmdobj.Guid, cmdobj.ID, ref customIn, ref customOut);
Workarounds:
a) I dont encourage you to replace the Visual C# 2005.vsk file, but if you want to investigate its this file:
C:\Program Files (x86)\Microsoft Visual Studio 1X.0\Common7\IDE\Visual C# 2005.vsk
MSDN Warning
You cannot programmatically change the settings for the default keyboard mapping scheme. To change the settings, save a copy of the default keyboard mapping scheme in the Keyboard node in the Options dialog box. You can then change the settings in that mapping scheme.
I do not recommend or encourage this method, its bad programming and you could destroy someone's keyboard shortcuts!
b) Another way could be by creating your own VSK file and setting it in the currentSettings.vssettings:
</ScopeDefinitions>
<ShortcutsScheme>Visual C# JT</ShortcutsScheme>
</KeyboardShortcuts>
Make sure you backup the currentSettings.vssettings file before changing it.
c) This leads back to Chris Dunaway's suggestion where you create a vssettings file (purely containing keyboard shortcuts) and import that in to reset the keyboard shortcuts. I realise the default shortcuts are not saved, however here is some code you can use with DTE to export the commands out, to insert into a new vssettings file to then import in:
//note, this is untested code!
public void Exec(string commandName, vsCommandExecOption executeOption, ref object varIn, ref object varOut, ref bool handled)
{
handled = false;
if(executeOption == vsCommandExecOption.vsCommandExecOptionDoDefault)
{
if(commandName == "ResetKeyBoard.Connect.ResetKeyBoard")
{
System.Diagnostics.Debug.WriteLine("<UserShortcuts>");
foreach (Command c in _applicationObject.Commands)
{
if (!string.IsNullOrEmpty(c.Name))
{
System.Array bindings = default(System.Array);
bindings = (System.Array)c.Bindings;
for (int i = 0; i <= bindings.Length - 1; i++)
{
string scope = string.Empty;
string keyShortCut = string.Empty;
string[] binding = bindings.GetValue(i).ToString().Split(new string[] { "::" },StringSplitOptions.RemoveEmptyEntries );
scope = binding[0];
keyShortCut = binding[1];
System.Diagnostics.Debug.WriteLine("<RemoveShortcut Command=\"...\" Scope=\"" + scope + "\">" + keyShortCut + "</RemoveShortcut>");
System.Diagnostics.Debug.WriteLine("<Shortcut Command=\"" + c.Name + "\" Scope=\"" + scope + "\">" + keyShortCut + "</Shortcut>");
}
}
}
System.Diagnostics.Debug.WriteLine("</UserShortcuts>");
Once you've got them out its easy to import them in:
_applicationObject.ExecuteCommand("Tools.ImportandExportSettings", "/import:\"KeyboardOnly-Exported-2016-08-29.vssettings\"");
REFs:
Visual Studio 2005 IDE Tips and Tricks
How to reset visual studio settings to my saved settings with just a single shortcut?
How does one set Visual Studio 2010 keyboard shortcuts comfortably, especially when using ReSharper?
https://superuser.com/questions/914244/is-there-a-quick-way-to-delete-all-shortcuts-in-visual-studio-10
Remove a keyboard shortcut binding in Visual Studio using Macros
http://vswindowmanager.codeplex.com/
Get full list of available commands for DTE.ExecuteCommand
HOWTO: Execute a command by Guid and Id from a Visual Studio package
HOWTO: Execute a command by Guid and Id from a Visual Studio add-in
HOWTO: Pass parameters programmatically to a command from a Visual Studio add-in
And finally this one by Jared Par:
https://github.com/jaredpar/VsVim/blob/master/Src/VsVimShared/Extensions.cs
/// <summary>
/// Safely reset the keyboard bindings on this Command to the provided values
/// </summary>
public static void SafeSetBindings(this DteCommand command, IEnumerable<string> commandBindings)
{
try
{
var bindings = commandBindings.Cast<object>().ToArray();
command.Bindings = bindings;
// There are certain commands in Visual Studio which simply don't want to have their
// keyboard bindings removed. The only way to get them to relinquish control is to
// ask them to remove the bindings twice.
//
// One example of this is SolutionExplorer.OpenFilesFilter. It has bindings for both
// "Ctrl-[, O" and "Ctrl-[, Ctrl-O". Asking it to remove all bindings will remove one
// but not both (at least until you restart Visual Studio, then both will be gone). If
// we ask it to remove bindings twice though then it will behave as expected.
if (bindings.Length == 0 && command.GetBindings().Count() != 0)
{
command.Bindings = bindings;
}
}
catch (Exception)
{
// Several implementations, Transact SQL in particular, return E_FAIL for this
// operation. Simply ignore the failure and continue
}
You can call devenv.exe directly and pass the /ResetSettings switch. Here is a link to the command line options for Visual Studio: https://msdn.microsoft.com/en-us/library/xee0c8y7.aspx
You can execute devenv.exe using the Systems.Diagnostics.Process class to reset the settings:
Devenv.exe /ResetSettings
You can, optionally, pass a settings file which contains the settings you want to restore:
Devenv.exe /ResetSettings "C:\My Files\MySettings.vssettings"
In Visual Studio, you can export selected settings by going to Tools > Import and Export Settings... and selecting "Export Selected Environment Settings". Then, only choose the Keyboard checkbox under the All Settings > Options > Environment subtree.

Localization works during debug, fails upon setup

I have a c# winform program which is translated to both Spanish and Portuguese. When debugging the program itself translates to the current windows chosen culture, and I also have a button to manually translate the program:
private void SetLanguage(string cul)
{
Thread.CurrentThread.CurrentUICulture = new CultureInfo(cul);
foreach (System.Windows.Forms.Control control in Controls)
{
var resources = new ComponentResourceManager(typeof(FrmLogin));
resources.ApplyResources(control, control.Name, new CultureInfo(cul));
}
}
but when I install said application (with the Setup solution in visual studio) nothing works. The program loads default language (Spanish) and the button to manually translate doesn't work.
I'm using visual studio 2010. "Localizable" property is set to true.
Thanks!

ILNumerics and Visual Studio Tools for Office (VSTO)

I've been experiemnting with the community version of ILNumerics 3.2.1.0 with .Net 4.0 in Visual Studio 2010 pro on Windows 7, and going through the documentation I succesfully get a windows form project to display a chart, using the code below.
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void ilPanel1_Load(object sender, EventArgs e)
{
ILSurface mySurface = new ILSurface(ILSpecialData.sincf(100, 200));
ILPlotCube myCube = new ILPlotCube(twoDMode: false);
myCube.Add(mySurface);
ilPanel1.Scene.Add(myCube);
}
}
If I try exactly the same code but from inside a VSTO Excel 2010 application all that is displayed in the form is the designer view of the ILPanel, blue circle on white background. I don't get any error messages. Am I missing something obvious? or does anyone have a solution of how to get the chart to display in VSTO?
Update
Thanks to Philliproso for pointing out the IsDesignMode() method. As pointed out in various places, including this question, Detecting design mode from a Control's constructor , the following method is not ideal, but for me is has provided a quick fix to allow me to evaluate ILNumerics.
public static bool IsDesignMode() {
if (System.Windows.Forms.Application.ExecutablePath.IndexOf("devenv.exe", StringComparison.OrdinalIgnoreCase) > -1)
{
return true;
}
return false;
}
This is the same issue as here:
Ilnumerics Ilpanel not activating when compiled in a winform into a dll when loaded into matlab
in-a-winform-into-a-dll-when-loa
Using VSTO as host for ILNumerics lets the panels assume, it was loaded in a designer. We are currently collecting possible workarounds and solutions. One solution might be to introduce a flag in the Settings of ILNumerics:
Hosted [default: false]
Your situation would require the flag to be enabled. In hosted mode, a blacklist of common designers could be checked at runtime and compared to the current entry assembly. Any other suggestions?

change textbox input language on change of app language

I am working on a metro app which provides a change language option in app. I want that on change of language textbox input language also get change. and it should not depends on system language.
I use these codes:
First of all you must find the name of the culture language you want.
method "GetInutLanguageByName" will return the language that you requested
Then you will check whether you installed the requested language or not, if yes then return the requested language.
Then change the input language very easy...
private static InputLanguage GetInutLanguageByName(string layOut)
{
foreach (InputLanguage lng in InputLanguage.InstalledInputLanguages)
{
if (lng.Culture.DisplayName == layOut)
{
return lng;
}
}
return null;
}
private void SetKeyboardLayout(InputLanguage Layout)
{
InputLanguage.CurrentInputLanguage = Layout;
}
private void FirstNameTextBox_Enter(object sender, EventArgs e)
{
SetKeyboardLayout(GetInutLanguageByName("Persian"));
}
Firstly, you need to make sure that the language you want is installed in OS, and it is in the list of INSTALLED INPUT LANGUAGES (check the language bar in control panel under Language and Regional Settings).. If its not in language bar, add it..
e.g. you want to change app language to "FRENCH".. you would need to create a new resource file for every language you want to change in app, and then change the current thread's Culture Property..
Are you familiar with resources file (.resx) and Culture Info Class??

Categories