Пример #1
0
        private void CreateShortcut(string path)
        {
            try
            {
                var link = (IShellLink) new ShellLink();

                link.SetPath(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                                          "LEProc.exe"));
                link.SetArguments($"-run \"{path}\"");
                link.SetIconLocation(AssociationReader.GetAssociatedIcon(Path.GetExtension(path)).Replace("%1", path), 0);

                link.SetDescription($"Run {Path.GetFileName(path)} with Locale Emulator");
                link.SetWorkingDirectory(Path.GetDirectoryName(path));

                var file = (IPersistFile)link;
                file.Save(
                    Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory),
                                 Path.GetFileNameWithoutExtension(path) + ".lnk"),
                    false);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message + "\r\n\r\n" + e.StackTrace);
            }
        }
Пример #2
0
        private void CreateShortcut(string path)
        {
            var shortcut =
                new WshShell().CreateShortcut(string.Format("{0}\\{1}.lnk",
                                                            Environment.GetFolderPath(Environment.SpecialFolder
                                                                                      .DesktopDirectory),
                                                            Path.GetFileNameWithoutExtension(path))) as IWshShortcut;

            if (shortcut == null)
            {
                MessageBox.Show("Create shortcut error", "LE", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            shortcut.TargetPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                                               "LEProc.exe");
            shortcut.Arguments        = String.Format("-run \"{0}\"", path);
            shortcut.WorkingDirectory = Path.GetDirectoryName(path);
            shortcut.WindowStyle      = 1;
            shortcut.Description      = string.Format("Run {0} with Locale Emulator", Path.GetFileName(path));
            shortcut.IconLocation     = AssociationReader.GetAssociatedIcon(Path.GetExtension(path)).Replace("%1", path);
            shortcut.Save();
        }
Пример #3
0
        private static void DoRunWithLEProfile(string path, LEProfile profile)
        {
            try
            {
                if (profile.RunAsAdmin && !SystemHelper.IsAdministrator())
                {
                    ElevateProcess();

                    return;
                }

                if (profile.RunWithSuspend)
                {
                    if (DialogResult.No ==
                        MessageBox.Show(
                            "You are running a exectuable with CREATE_SUSPENDED flag.\r\n" +
                            "\r\n" +
                            "The exectuable will be executed after you click the \"Yes\" button, " +
                            "But as a background process which has no notfications at all." +
                            "You can attach it by using OllyDbg, or stop it with Task Manager.\r\n",
                            "Locale Emulator Debug Mode Warning",
                            MessageBoxButtons.YesNo,
                            MessageBoxIcon.Information
                            ))
                    {
                        return;
                    }
                }

                var applicationName = string.Empty;
                var commandLine     = string.Empty;

                if (Path.GetExtension(path).ToLower() == ".exe")
                {
                    applicationName = path;

                    commandLine = path.StartsWith("\"")
                                      ? string.Format("{0} ", path)
                                      : String.Format("\"{0}\" ", path);

                    commandLine += profile.Parameter;
                }
                else
                {
                    var jb = AssociationReader.GetAssociatedProgram(Path.GetExtension(path));

                    if (jb == null)
                    {
                        return;
                    }

                    applicationName = jb[0];

                    commandLine = jb[0].StartsWith("\"")
                                      ? string.Format("{0} ", jb[0])
                                      : String.Format("\"{0}\" ", jb[0]);
                    commandLine += jb[1].Replace("%1", path).Replace("%*", profile.Parameter);
                }

                var currentDirectory = Path.GetDirectoryName(path);
                var debugMode        = profile.RunWithSuspend;
                var ansiCodePage     = (uint)CultureInfo.GetCultureInfo(profile.Location).TextInfo.ANSICodePage;
                var oemCodePage      = (uint)CultureInfo.GetCultureInfo(profile.Location).TextInfo.OEMCodePage;
                var localeID         = (uint)CultureInfo.GetCultureInfo(profile.Location).TextInfo.LCID;
                var defaultCharset   = (uint)
                                       GetCharsetFromANSICodepage(CultureInfo.GetCultureInfo(profile.Location)
                                                                  .TextInfo.ANSICodePage);

                var tzi          = TimeZoneInfo.FindSystemTimeZoneById(profile.Timezone);
                var timezoneBias = (int)-tzi.BaseUtcOffset.TotalMinutes;

                var adjustmentRules = tzi.GetAdjustmentRules();
                TimeZoneInfo.AdjustmentRule adjustmentRule = null;
                if (adjustmentRules.Length > 0)
                {
                    // Find the single record that encompasses today's date. If none exists, sets adjustmentRule to null.
                    adjustmentRule =
                        adjustmentRules.SingleOrDefault(ar => ar.DateStart <= DateTime.Now && DateTime.Now <= ar.DateEnd);
                }
                var timezoneDaylightBias = adjustmentRule == null ? 0 : (int)-adjustmentRule.DaylightDelta.TotalMinutes;

                var timezoneStandardName = tzi.StandardName;

                var timezoneDaylightName = tzi.DaylightName;

                var registries = profile.RedirectRegistry
                                     ? new LERegistry().GetRegistryEntries()
                                     : new LERegistryEntry[0];

                var l = new LoaderWrapper
                {
                    ApplicationName      = applicationName,
                    CommandLine          = commandLine,
                    CurrentDirectory     = currentDirectory,
                    AnsiCodePage         = ansiCodePage,
                    OemCodePage          = oemCodePage,
                    LocaleID             = localeID,
                    DefaultCharset       = defaultCharset,
                    TimezoneBias         = timezoneBias,
                    TimezoneDaylightBias = timezoneDaylightBias,
                    TimezoneStandardName = timezoneStandardName,
                    TimezoneDaylightName = timezoneDaylightName,
                    NumberOfRegistryRedirectionEntries = registries.Length,
                    DebugMode = debugMode
                };

                registries.ToList()
                .ForEach(
                    item =>
                    l.AddRegistryRedirectEntry(item.Root, item.Key, item.Name, item.Type, item.Data));

                uint ret;
                if ((ret = l.Start()) != 0)
                {
                    if (SystemHelper.IsAdministrator())
                    {
                        GlobalHelper.ShowErrorDebugMessageBox(commandLine, ret);
                    }
                    else
                    {
                        ElevateProcess();
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }
Пример #4
0
        private static void DoRunWithLEProfile(string absPath, int argumentsStart, LEProfile profile)
        {
            try
            {
                if (profile.RunAsAdmin && !SystemHelper.IsAdministrator())
                {
                    ElevateProcess();

                    return;
                }

                if (profile.RunWithSuspend)
                {
                    if (DialogResult.No ==
                        MessageBox.Show(
                            "You are running a exectuable with CREATE_SUSPENDED flag.\r\n" +
                            "\r\n" +
                            "The exectuable will be executed after you click the \"Yes\" button, " +
                            "but as a background process which has no notifications at all." +
                            "You can attach it by using OllyDbg, or stop it with Task Manager.\r\n",
                            "Locale Emulator Debug Mode Warning",
                            MessageBoxButtons.YesNo,
                            MessageBoxIcon.Information
                            ))
                    {
                        return;
                    }
                }

                var applicationName = string.Empty;
                var commandLine     = string.Empty;

                if (Path.GetExtension(absPath).ToLower() == ".exe")
                {
                    applicationName = absPath;

                    commandLine = absPath.StartsWith("\"")
                        ? $"{absPath} "
                        : $"\"{absPath}\" ";

                    // use arguments in le.config, prior to command line arguments
                    commandLine += string.IsNullOrEmpty(profile.Parameter) && Args.Skip(argumentsStart).Any()
                        ? Args.Skip(argumentsStart).Aggregate((a, b) => $"{a} {b}")
                        : profile.Parameter;
                }
                else
                {
                    var jb = AssociationReader.GetAssociatedProgram(Path.GetExtension(absPath));

                    if (jb == null)
                    {
                        return;
                    }

                    applicationName = jb[0];

                    commandLine = jb[0].StartsWith("\"")
                        ? $"{jb[0]} "
                        : $"\"{jb[0]}\" ";
                    commandLine += jb[1].Replace("%1", absPath).Replace("%*", profile.Parameter);
                }

                var currentDirectory = Path.GetDirectoryName(absPath);
                var ansiCodePage     = (uint)CultureInfo.GetCultureInfo(profile.Location).TextInfo.ANSICodePage;
                var oemCodePage      = (uint)CultureInfo.GetCultureInfo(profile.Location).TextInfo.OEMCodePage;
                var localeID         = (uint)CultureInfo.GetCultureInfo(profile.Location).TextInfo.LCID;
                var defaultCharset   = (uint)
                                       GetCharsetFromANSICodepage(CultureInfo.GetCultureInfo(profile.Location)
                                                                  .TextInfo.ANSICodePage);

                var registries = profile.RedirectRegistry
                    ? RegistryEntriesLoader.GetRegistryEntries(profile.IsAdvancedRedirection)
                    : null;

                var l = new LoaderWrapper
                {
                    ApplicationName   = applicationName,
                    CommandLine       = commandLine,
                    CurrentDirectory  = currentDirectory,
                    AnsiCodePage      = ansiCodePage,
                    OemCodePage       = oemCodePage,
                    LocaleID          = localeID,
                    DefaultCharset    = defaultCharset,
                    HookUILanguageAPI = profile.IsAdvancedRedirection ? (uint)1 : 0,
                    Timezone          = profile.Timezone,
                    NumberOfRegistryRedirectionEntries = registries?.Length ?? 0,
                    DebugMode = profile.RunWithSuspend
                };

                registries?.ToList()
                .ForEach(
                    item =>
                    l.AddRegistryRedirectEntry(item.Root,
                                               item.Key,
                                               item.Name,
                                               item.Type,
                                               item.GetValue(CultureInfo.GetCultureInfo(profile.Location))));

                uint ret;
                if ((ret = l.Start()) != 0)
                {
                    if (SystemHelper.IsAdministrator())
                    {
                        GlobalHelper.ShowErrorDebugMessageBox(commandLine, ret);
                    }
                    else
                    {
                        ElevateProcess();
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }
Пример #5
0
        private static void DoRunWithLEProfile(string path, LEProfile profile)
        {
            try
            {
                if (profile.RunAsAdmin && !SystemHelper.IsAdministrator())
                {
                    ElevateProcess();

                    return;
                }

                if (profile.RunWithSuspend)
                {
                    if (DialogResult.No ==
                        MessageBox.Show(
                            "You are running a exectuable with CREATE_SUSPENDED flag.\r\n" +
                            "\r\n" +
                            "The exectuable will be executed after you click the \"Yes\" button, " +
                            "But as a background process which has no notfications at all." +
                            "You can attach it by using OllyDbg, or stop it with Task Manager.\r\n",
                            "Locale Emulator Debug Mode Warning",
                            MessageBoxButtons.YesNo,
                            MessageBoxIcon.Information
                            ))
                    {
                        return;
                    }
                }

                string applicationName = string.Empty;
                string commandLine     = string.Empty;

                if (Path.GetExtension(path).ToLower() == ".exe")
                {
                    applicationName = path;

                    commandLine = path.StartsWith("\"")
                                      ? string.Format("{0} ", path)
                                      : String.Format("\"{0}\" ", path);

                    commandLine += profile.Parameter;
                }
                else
                {
                    string[] jb = AssociationReader.GetAssociatedProgram(Path.GetExtension(path));

                    if (jb == null)
                    {
                        return;
                    }

                    applicationName = jb[0];

                    commandLine = jb[0].StartsWith("\"")
                                      ? string.Format("{0} ", jb[0])
                                      : String.Format("\"{0}\" ", jb[0]);
                    commandLine += jb[1].Replace("%1", path).Replace("%*", profile.Parameter);
                }

                string currentDirectory = Path.GetDirectoryName(path);
                bool   debugMode        = profile.RunWithSuspend;
                var    ansiCodePage     = (uint)CultureInfo.GetCultureInfo(profile.Location).TextInfo.ANSICodePage;
                var    oemCodePage      = (uint)CultureInfo.GetCultureInfo(profile.Location).TextInfo.OEMCodePage;
                var    localeID         = (uint)CultureInfo.GetCultureInfo(profile.Location).TextInfo.LCID;
                var    defaultCharset   = (uint)
                                          GetCharsetFromANSICodepage(CultureInfo.GetCultureInfo(profile.Location)
                                                                     .TextInfo.ANSICodePage);

                TimeZoneInfo tzi          = TimeZoneInfo.FindSystemTimeZoneById(profile.Timezone);
                var          timezoneBias = (int)-tzi.BaseUtcOffset.TotalMinutes;

                TimeZoneInfo.AdjustmentRule[] adjustmentRules = tzi.GetAdjustmentRules();
                TimeZoneInfo.AdjustmentRule   adjustmentRule  = null;
                if (adjustmentRules.Length > 0)
                {
                    // Find the single record that encompasses today's date. If none exists, sets adjustmentRule to null.
                    adjustmentRule =
                        adjustmentRules.SingleOrDefault(ar => ar.DateStart <= DateTime.Now && DateTime.Now <= ar.DateEnd);
                }
                int timezoneDaylightBias = adjustmentRule == null ? 0 : (int)-adjustmentRule.DaylightDelta.TotalMinutes;

                string timezoneStandardName = tzi.StandardName;

                string timezoneDaylightName = tzi.DaylightName;

                LERegistryEntry[] registries = profile.RedirectRegistry
                                                   ? new LERegistry().GetRegistryEntries()
                                                   : new LERegistryEntry[0];

                var l = new LoaderWrapper
                {
                    ApplicationName      = applicationName,
                    CommandLine          = commandLine,
                    CurrentDirectory     = currentDirectory,
                    AnsiCodePage         = ansiCodePage,
                    OemCodePage          = oemCodePage,
                    LocaleID             = localeID,
                    DefaultCharset       = defaultCharset,
                    TimezoneBias         = timezoneBias,
                    TimezoneDaylightBias = timezoneDaylightBias,
                    TimezoneStandardName = timezoneStandardName,
                    TimezoneDaylightName = timezoneDaylightName,
                    NumberOfRegistryRedirectionEntries = registries.Length,
                    DebugMode = debugMode,
                };

                registries.ToList()
                .ForEach(
                    item =>
                    l.AddRegistryRedirectEntry(item.Root, item.Key, item.Name, item.Type, item.Data));

                uint ret;
                if ((ret = l.Start()) != 0)
                {
                    if (SystemHelper.IsAdministrator())
                    {
                        MessageBox.Show(String.Format(
                                            "Launch failed.\r\n" +
                                            "\r\n" +
                                            "Commands: {0}\r\n" +
                                            "Error Number: {1}\r\n" +
                                            "Administrator: {2}\r\n" +
                                            "\r\n" +
                                            "If you have any antivirus software running, please turn it off and try again.\r\n"
                                            +
                                            "If you think this error is related to LE itself, feel free to submit an issue at\r\n"
                                            +
                                            "https://github.com/xupefei/Locale-Emulator/issues.\r\n" +
                                            "\r\n" +
                                            "\r\n" +
                                            "You can press CTRL+C to copy this message to your clipboard.\r\n",
                                            commandLine,
                                            Convert.ToString(ret, 16).ToUpper(),
                                            SystemHelper.IsAdministrator()
                                            ),
                                        "Locale Emulator Version " + GlobalHelper.GetLEVersion());
                    }
                    else
                    {
                        ElevateProcess();
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }
        /// <summary>
        ///     Initialize the context menu handler.
        /// </summary>
        /// <param name="pidlFolder">
        ///     A pointer to an ITEMIDLIST structure that uniquely identifies a folder.
        /// </param>
        /// <param name="pDataObj">
        ///     A pointer to an IDataObject interface object that can be used to retrieve
        ///     the objects being acted upon.
        /// </param>
        /// <param name="hKeyProgId">
        ///     The registry key for the file object or folder type.
        /// </param>
        public void Initialize(IntPtr pidlFolder, IntPtr pDataObj, IntPtr hKeyProgId)
        {
            if (pDataObj == IntPtr.Zero)
            {
                throw new ArgumentException();
            }

            var fe = new FORMATETC
            {
                cfFormat = (short)CLIPFORMAT.CF_HDROP,
                ptd      = IntPtr.Zero,
                dwAspect = DVASPECT.DVASPECT_CONTENT,
                lindex   = -1,
                tymed    = TYMED.TYMED_HGLOBAL
            };
            STGMEDIUM stm;

            // The pDataObj pointer contains the objects being acted upon. In this
            // example, we get an HDROP handle for enumerating the selected files
            // and folders.
            var dataObject = (IDataObject)Marshal.GetObjectForIUnknown(pDataObj);

            dataObject.GetData(ref fe, out stm);

            try
            {
                // Get an HDROP handle.
                var hDrop = stm.unionmember;
                if (hDrop == IntPtr.Zero)
                {
                    throw new ArgumentException();
                }

                // Determine how many files are involved in this operation.
                var nFiles = NativeMethods.DragQueryFile(hDrop, uint.MaxValue, null, 0);

                // This code sample displays the custom context menu item when only
                // one file is selected.
                if (nFiles == 1)
                {
                    // Get the path of the file.
                    var fileName = new StringBuilder(260);
                    if (0 == NativeMethods.DragQueryFile(hDrop,
                                                         0,
                                                         fileName,
                                                         fileName.Capacity))
                    {
                        Marshal.ThrowExceptionForHR(WinError.E_FAIL);
                    }

                    _selectedFile = fileName.ToString();

                    // Check exe binary type
                    var path = string.Empty;
                    var ext  = Path.GetExtension(_selectedFile).ToLower();

                    if (ext == ".exe")
                    {
                        path = _selectedFile;
                    }
                    else
                    {
                        path = AssociationReader.HaveAssociatedProgram(ext)
                                   ? AssociationReader.GetAssociatedProgram(ext)[0]
                                   : string.Empty;

                        if (SystemHelper.Is64BitOS())
                        {
                            path = SystemHelper.RedirectToWow64(path);
                        }
                    }
                    // Do not display context menus for 64bit exe.
                    switch (PEFileReader.GetPEType(path))
                    {
                    case PEType.Unknown:
                    case PEType.X64:
                        Marshal.ThrowExceptionForHR(WinError.E_FAIL);
                        break;

                    case PEType.X32:
                        break;
                    }
                }
                else
                {
                    Marshal.ThrowExceptionForHR(WinError.E_FAIL);
                }
            }
            finally
            {
                NativeMethods.ReleaseStgMedium(ref stm);
            }
        }
Пример #7
0
        private static void DoRunWithLEProfile(string path, LEProfile profile)
        {
            try
            {
                if (profile.RunWithSuspend)
                {
                    if (DialogResult.No ==
                        MessageBox.Show(
                            "You are running a process with CREATE_SUSPEND flag.\r\nIs this really what you want?",
                            "Locale Emulator Debug Mode Warning", MessageBoxButtons.YesNo)) return;
                }

                string applicationName = string.Empty;
                string commandLine = string.Empty;

                if (Path.GetExtension(path).ToLower() == ".exe")
                {
                    applicationName = path;

                    commandLine = path.StartsWith("\"")
                                      ? string.Format("{0} ", path)
                                      : String.Format("\"{0}\" ", path);

                    commandLine += profile.Parameter;
                }
                else
                {
                    string[] jb = AssociationReader.GetAssociatedProgram(Path.GetExtension(path));

                    if (jb == null)
                        return;

                    applicationName = jb[0];

                    commandLine = jb[0].StartsWith("\"")
                                      ? string.Format("{0} ", jb[0])
                                      : String.Format("\"{0}\" ", jb[0]);
                    commandLine += jb[1].Replace("%1", path).Replace("%*", profile.Parameter);
                }

                string currentDirectory = Path.GetDirectoryName(path);
                bool debugMode = profile.RunWithSuspend;
                var ansiCodePage = (uint)CultureInfo.GetCultureInfo(profile.Location).TextInfo.ANSICodePage;
                var oemCodePage = (uint)CultureInfo.GetCultureInfo(profile.Location).TextInfo.OEMCodePage;
                var localeID = (uint)CultureInfo.GetCultureInfo(profile.Location).TextInfo.LCID;
                var defaultCharset = (uint)
                                     GetCharsetFromANSICodepage(
                                         CultureInfo.GetCultureInfo(profile.Location).TextInfo.ANSICodePage);
                string defaultFaceName = profile.DefaultFont;

                TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById(profile.Timezone);
                var timezoneBias = (int)-tzi.BaseUtcOffset.TotalMinutes;

                TimeZoneInfo.AdjustmentRule[] adjustmentRules = tzi.GetAdjustmentRules();
                TimeZoneInfo.AdjustmentRule adjustmentRule = null;
                if (adjustmentRules.Length > 0)
                {
                    // Find the single record that encompasses today's date. If none exists, sets adjustmentRule to null.
                    adjustmentRule =
                        adjustmentRules.SingleOrDefault(ar => ar.DateStart <= DateTime.Now && DateTime.Now <= ar.DateEnd);
                }
                int timezoneDaylightBias = adjustmentRule == null ? 0 : (int)-adjustmentRule.DaylightDelta.TotalMinutes;

                string timezoneStandardName = tzi.StandardName;

                string timezoneDaylightName = tzi.DaylightName;

                var l = new LoaderWrapper
                    {
                        ApplicationName = applicationName,
                        CommandLine = commandLine,
                        CurrentDirectory = currentDirectory,
                        AnsiCodePage = ansiCodePage,
                        OemCodePage = oemCodePage,
                        LocaleID = localeID,
                        DefaultCharset = defaultCharset,
                        DefaultFaceName = defaultFaceName,
                        TimezoneBias = timezoneBias,
                        TimezoneDaylightBias = timezoneDaylightBias,
                        TimezoneStandardName = timezoneStandardName,
                        TimezoneDaylightName = timezoneDaylightName,
                        DebugMode = debugMode,
                    };

                uint ret;
                if ((ret = l.Start()) != 0)
                {
                    if (IsAdministrator())
                    {
                        MessageBox.Show(
                            String.Format(
                                "Error number {0} detected.\r\n\r\nThis may because the target executable is a 64-bit binary which is not supported by the current version of Locale Emulator.",
                                Convert.ToString(ret, 16).ToUpper()),
                            "Locale Emulator");
                    }
                    else
                    {
                        RunWithElevatedProcess(Args);
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }