// Workaround for only partially visible list view items /* public static void EnsureVisible(ListView lv, int nIndex, bool bPartialOK) * { * Debug.Assert(lv != null); if(lv == null) return; * Debug.Assert(nIndex >= 0); if(nIndex < 0) return; * Debug.Assert(nIndex < lv.Items.Count); if(nIndex >= lv.Items.Count) return; * * int nPartialOK = (bPartialOK ? 1 : 0); * try * { * NativeMethods.SendMessage(lv.Handle, LVM_ENSUREVISIBLE, * new IntPtr(nIndex), new IntPtr(nPartialOK)); * } * catch(Exception) { Debug.Assert(false); } * } */ public static int GetScrollPosY(IntPtr hWnd) { if (NativeLib.IsUnix()) { return(0); } try { SCROLLINFO si = new SCROLLINFO(); si.cbSize = (uint)Marshal.SizeOf(si); si.fMask = (uint)ScrollInfoMask.SIF_POS; if (GetScrollInfo(hWnd, (int)ScrollBarDirection.SB_VERT, ref si)) { return(si.nPos); } Debug.Assert(false); } catch (Exception) { Debug.Assert(false); } return(0); }
internal static bool PerformGlobal(List <PwDatabase> lSources, ImageList ilIcons, string strSeq) { if (lSources == null) { Debug.Assert(false); return(false); } if (NativeLib.IsUnix()) { if (!NativeMethods.TryXDoTool(true) && !NativeLib.IsWayland()) { MessageService.ShowWarning(KPRes.AutoTypeXDoToolRequiredGlobalVer); return(false); } } IntPtr hWnd; string strWindow; try { // hWnd = NativeMethods.GetForegroundWindowHandle(); // strWindow = NativeMethods.GetWindowText(hWnd); NativeMethods.GetForegroundWindowInfo(out hWnd, out strWindow, true); } catch (Exception) { Debug.Assert(false); hWnd = IntPtr.Zero; strWindow = null; } // if(string.IsNullOrEmpty(strWindow)) return false; if (strWindow == null) { Debug.Assert(false); return(false); } if (!IsValidAutoTypeWindow(hWnd, true)) { return(false); } SequenceQueriesEventArgs evQueries = GetSequencesForWindowBegin( hWnd, strWindow); List <AutoTypeCtx> lCtxs = new List <AutoTypeCtx>(); PwDatabase pdCurrent = null; bool bExpCanMatch = Program.Config.Integration.AutoTypeExpiredCanMatch; DateTime dtNow = DateTime.UtcNow; EntryHandler eh = delegate(PwEntry pe) { if (!bExpCanMatch && pe.Expires && (pe.ExpiryTime <= dtNow)) { return(true); // Ignore expired entries } List <string> lSeq = GetSequencesForWindow(pe, hWnd, strWindow, pdCurrent, evQueries.EventID); if (!string.IsNullOrEmpty(strSeq) && (lSeq.Count != 0)) { lCtxs.Add(new AutoTypeCtx(strSeq, pe, pdCurrent)); } else { foreach (string strSeqCand in lSeq) { lCtxs.Add(new AutoTypeCtx(strSeqCand, pe, pdCurrent)); } } return(true); }; foreach (PwDatabase pd in lSources) { if ((pd == null) || !pd.IsOpen) { continue; } pdCurrent = pd; pd.RootGroup.TraverseTree(TraversalMethod.PreOrder, null, eh); } GetSequencesForWindowEnd(evQueries); bool bForceDlg = Program.Config.Integration.AutoTypeAlwaysShowSelDialog; if ((lCtxs.Count >= 2) || bForceDlg) { AutoTypeCtxForm dlg = new AutoTypeCtxForm(); dlg.InitEx(lCtxs, ilIcons); bool bOK = (dlg.ShowDialog() == DialogResult.OK); AutoTypeCtx ctx = (bOK ? dlg.SelectedCtx : null); UIUtil.DestroyForm(dlg); if (ctx != null) { try { NativeMethods.EnsureForegroundWindow(hWnd); } catch (Exception) { Debug.Assert(false); } int nActDelayMS = TargetActivationDelay; string strWindowT = strWindow.Trim(); // https://sourceforge.net/p/keepass/discussion/329220/thread/3681f343/ // This apparently is only required here (after showing the // auto-type entry selection dialog), not when using the // context menu command in the main window if (strWindowT.EndsWith("Microsoft Edge", StrUtil.CaseIgnoreCmp)) { // 700 skips the first 1-2 characters, // 750 sometimes skips the first character nActDelayMS = 1000; } // Allow target window to handle its activation // (required by some applications, e.g. Edge) Application.DoEvents(); Thread.Sleep(nActDelayMS); Application.DoEvents(); AutoType.PerformInternal(ctx, strWindow); } } else if (lCtxs.Count == 1) { AutoType.PerformInternal(lCtxs[0], strWindow); } return(true); }
private static bool Execute(AutoTypeCtx ctx) { if (ctx == null) { Debug.Assert(false); return(false); } string strSeq = ctx.Sequence; PwEntry pweData = ctx.Entry; if (pweData == null) { Debug.Assert(false); return(false); } if (!pweData.GetAutoTypeEnabled()) { return(false); } if (!AppPolicy.Try(AppPolicyId.AutoType)) { return(false); } if (NativeLib.IsUnix()) { if (!NativeMethods.TryXDoTool() && !NativeLib.IsWayland()) { MessageService.ShowWarning(KPRes.AutoTypeXDoToolRequired, KPRes.PackageInstallHint); return(false); } } PwDatabase pwDatabase = ctx.Database; bool bObfuscate = (pweData.AutoType.ObfuscationOptions != AutoTypeObfuscationOptions.None); AutoTypeEventArgs args = new AutoTypeEventArgs(strSeq, bObfuscate, pweData, pwDatabase); if (AutoType.FilterCompilePre != null) { AutoType.FilterCompilePre(null, args); } args.Sequence = SprEngine.Compile(args.Sequence, new SprContext( pweData, pwDatabase, SprCompileFlags.All, true, false)); // string strError = ValidateAutoTypeSequence(args.Sequence); // if(!string.IsNullOrEmpty(strError)) // { // MessageService.ShowWarning(args.Sequence + // MessageService.NewParagraph + strError); // return false; // } Application.DoEvents(); if (AutoType.FilterSendPre != null) { AutoType.FilterSendPre(null, args); } if (AutoType.FilterSend != null) { AutoType.FilterSend(null, args); } if (args.Sequence.Length > 0) { string strError = null; try { SendInputEx.SendKeysWait(args.Sequence, args.SendObfuscated); } catch (SecurityException exSec) { strError = exSec.Message; } catch (Exception ex) { strError = args.Sequence + MessageService.NewParagraph + ex.Message; } if (AutoType.SendPost != null) { AutoType.SendPost(null, args); } if (!string.IsNullOrEmpty(strError)) { try { MainForm mfP = Program.MainForm; if (mfP != null) { mfP.EnsureVisibleForegroundWindow(false, false); } } catch (Exception) { Debug.Assert(false); } MessageService.ShowWarning(strError); } } pweData.Touch(false); EntryUtil.ExpireTanEntryIfOption(pweData, pwDatabase); MainForm mf = Program.MainForm; if (mf != null) { // Always refresh entry list (e.g. {NEWPASSWORD} might // have changed data) mf.RefreshEntriesList(); // SprEngine.Compile might have modified the database; // pd.Modified is set by SprEngine mf.UpdateUI(false, null, false, null, false, null, false); if (Program.Config.MainWindow.MinimizeAfterAutoType && mf.IsCommandTypeInvokable(null, MainForm.AppCommandType.Window)) { UIUtil.SetWindowState(mf, FormWindowState.Minimized); } } return(true); }
public static void Main(string[] args) { #if DEBUG // Program.DesignMode should not be queried before executing // Main (e.g. by a static Control) when running the program // normally Debug.Assert(!m_bDesignModeQueried); #endif m_bDesignMode = false; // Designer doesn't call Main method m_cmdLineArgs = new CommandLineArgs(args); // Before loading the configuration string strWaDisable = m_cmdLineArgs[ AppDefs.CommandLineOptions.WorkaroundDisable]; if (!string.IsNullOrEmpty(strWaDisable)) { MonoWorkarounds.SetEnabled(strWaDisable, false); } DpiUtil.ConfigureProcess(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.DoEvents(); // Required #if DEBUG string strInitialWorkDir = WinUtil.GetWorkingDirectory(); #endif if (!CommonInit()) { CommonTerminate(); return; } if (m_appConfig.Application.Start.PluginCacheClearOnce) { PlgxCache.Clear(); m_appConfig.Application.Start.PluginCacheClearOnce = false; AppConfigSerializer.Save(Program.Config); } if (m_cmdLineArgs[AppDefs.CommandLineOptions.FileExtRegister] != null) { ShellUtil.RegisterExtension(AppDefs.FileExtension.FileExt, AppDefs.FileExtension.ExtId, KPRes.FileExtName, WinUtil.GetExecutable(), PwDefs.ShortProductName, false); MainCleanUp(); return; } if (m_cmdLineArgs[AppDefs.CommandLineOptions.FileExtUnregister] != null) { ShellUtil.UnregisterExtension(AppDefs.FileExtension.FileExt, AppDefs.FileExtension.ExtId); MainCleanUp(); return; } if (m_cmdLineArgs[AppDefs.CommandLineOptions.PreLoad] != null) { // All important .NET assemblies are in memory now already try { SelfTest.Perform(); } catch (Exception) { Debug.Assert(false); } MainCleanUp(); return; } /* if(m_cmdLineArgs[AppDefs.CommandLineOptions.PreLoadRegister] != null) * { * string strPreLoadPath = WinUtil.GetExecutable().Trim(); * if(strPreLoadPath.StartsWith("\"") == false) * strPreLoadPath = "\"" + strPreLoadPath + "\""; * ShellUtil.RegisterPreLoad(AppDefs.PreLoadName, strPreLoadPath, * @"--" + AppDefs.CommandLineOptions.PreLoad, true); * MainCleanUp(); * return; * } * if(m_cmdLineArgs[AppDefs.CommandLineOptions.PreLoadUnregister] != null) * { * ShellUtil.RegisterPreLoad(AppDefs.PreLoadName, string.Empty, * string.Empty, false); * MainCleanUp(); * return; * } */ if ((m_cmdLineArgs[AppDefs.CommandLineOptions.Help] != null) || (m_cmdLineArgs[AppDefs.CommandLineOptions.HelpLong] != null)) { AppHelp.ShowHelp(AppDefs.HelpTopics.CommandLine, null); MainCleanUp(); return; } if (m_cmdLineArgs[AppDefs.CommandLineOptions.ConfigSetUrlOverride] != null) { Program.Config.Integration.UrlOverride = m_cmdLineArgs[ AppDefs.CommandLineOptions.ConfigSetUrlOverride]; AppConfigSerializer.Save(Program.Config); MainCleanUp(); return; } if (m_cmdLineArgs[AppDefs.CommandLineOptions.ConfigClearUrlOverride] != null) { Program.Config.Integration.UrlOverride = string.Empty; AppConfigSerializer.Save(Program.Config); MainCleanUp(); return; } if (m_cmdLineArgs[AppDefs.CommandLineOptions.ConfigGetUrlOverride] != null) { try { string strFileOut = UrlUtil.EnsureTerminatingSeparator( UrlUtil.GetTempPath(), false) + "KeePass_UrlOverride.tmp"; string strContent = ("[KeePass]\r\nKeeURLOverride=" + Program.Config.Integration.UrlOverride + "\r\n"); File.WriteAllText(strFileOut, strContent); } catch (Exception) { Debug.Assert(false); } MainCleanUp(); return; } if (m_cmdLineArgs[AppDefs.CommandLineOptions.ConfigSetLanguageFile] != null) { Program.Config.Application.LanguageFile = m_cmdLineArgs[ AppDefs.CommandLineOptions.ConfigSetLanguageFile]; AppConfigSerializer.Save(Program.Config); MainCleanUp(); return; } if (m_cmdLineArgs[AppDefs.CommandLineOptions.PlgxCreate] != null) { PlgxPlugin.CreateFromCommandLine(); MainCleanUp(); return; } if (m_cmdLineArgs[AppDefs.CommandLineOptions.PlgxCreateInfo] != null) { PlgxPlugin.CreateInfoFile(m_cmdLineArgs.FileName); MainCleanUp(); return; } if (m_cmdLineArgs[AppDefs.CommandLineOptions.ShowAssemblyInfo] != null) { MessageService.ShowInfo(Assembly.GetExecutingAssembly().ToString()); MainCleanUp(); return; } if (m_cmdLineArgs[AppDefs.CommandLineOptions.MakeXmlSerializerEx] != null) { XmlSerializerEx.GenerateSerializers(m_cmdLineArgs); MainCleanUp(); return; } if (m_cmdLineArgs[AppDefs.CommandLineOptions.MakeXspFile] != null) { XspArchive.CreateFile(m_cmdLineArgs.FileName, m_cmdLineArgs["d"]); MainCleanUp(); return; } if (m_cmdLineArgs[AppDefs.CommandLineOptions.Version] != null) { Console.WriteLine(PwDefs.ShortProductName + " " + PwDefs.VersionString); Console.WriteLine(PwDefs.Copyright); MainCleanUp(); return; } #if DEBUG if (m_cmdLineArgs[AppDefs.CommandLineOptions.TestGfx] != null) { List <Image> lImg = new List <Image>(); lImg.Add(Properties.Resources.B16x16_Browser); lImg.Add(Properties.Resources.B48x48_Keyboard_Layout); ImageArchive aHighRes = new ImageArchive(); aHighRes.Load(Properties.Resources.Images_Client_HighRes); lImg.Add(aHighRes.GetForObject("C12_IRKickFlash")); if (File.Exists("Test.png")) { lImg.Add(Image.FromFile("Test.png")); } Image img = GfxUtil.ScaleTest(lImg.ToArray()); img.Save("GfxScaleTest.png", ImageFormat.Png); return; } #endif // #if (DEBUG && !KeePassLibSD) // if(m_cmdLineArgs[AppDefs.CommandLineOptions.MakePopularPasswordTable] != null) // { // PopularPasswords.MakeList(); // MainCleanUp(); // return; // } // #endif try { m_nAppMessage = NativeMethods.RegisterWindowMessage(m_strWndMsgID); } catch (Exception) { Debug.Assert(NativeLib.IsUnix()); } if (m_cmdLineArgs[AppDefs.CommandLineOptions.ExitAll] != null) { BroadcastAppMessageAndCleanUp(AppMessage.Exit); return; } if (m_cmdLineArgs[AppDefs.CommandLineOptions.AutoType] != null) { BroadcastAppMessageAndCleanUp(AppMessage.AutoType); return; } if (m_cmdLineArgs[AppDefs.CommandLineOptions.AutoTypeSelected] != null) { BroadcastAppMessageAndCleanUp(AppMessage.AutoTypeSelected); return; } if (m_cmdLineArgs[AppDefs.CommandLineOptions.OpenEntryUrl] != null) { string strEntryUuid = m_cmdLineArgs[AppDefs.CommandLineOptions.Uuid]; if (!string.IsNullOrEmpty(strEntryUuid)) { IpcParamEx ipUrl = new IpcParamEx(IpcUtilEx.CmdOpenEntryUrl, strEntryUuid, null, null, null, null); IpcUtilEx.SendGlobalMessage(ipUrl); } MainCleanUp(); return; } if (m_cmdLineArgs[AppDefs.CommandLineOptions.LockAll] != null) { BroadcastAppMessageAndCleanUp(AppMessage.Lock); return; } if (m_cmdLineArgs[AppDefs.CommandLineOptions.UnlockAll] != null) { BroadcastAppMessageAndCleanUp(AppMessage.Unlock); return; } if (m_cmdLineArgs[AppDefs.CommandLineOptions.IpcEvent] != null) { string strName = m_cmdLineArgs[AppDefs.CommandLineOptions.IpcEvent]; if (!string.IsNullOrEmpty(strName)) { string[] vFlt = KeyUtil.MakeCtxIndependent(args); IpcParamEx ipEvent = new IpcParamEx(IpcUtilEx.CmdIpcEvent, strName, CommandLineArgs.SafeSerialize(vFlt), null, null, null); IpcUtilEx.SendGlobalMessage(ipEvent); } MainCleanUp(); return; } // Mutex mSingleLock = TrySingleInstanceLock(AppDefs.MutexName, true); bool bSingleLock = GlobalMutexPool.CreateMutex(AppDefs.MutexName, true); // if((mSingleLock == null) && m_appConfig.Integration.LimitToSingleInstance) if (!bSingleLock && m_appConfig.Integration.LimitToSingleInstance) { ActivatePreviousInstance(args); MainCleanUp(); return; } Mutex mGlobalNotify = TryGlobalInstanceNotify(AppDefs.MutexNameGlobal); AutoType.InitStatic(); CustomMessageFilterEx cmfx = new CustomMessageFilterEx(); Application.AddMessageFilter(cmfx); #if DEBUG if (m_cmdLineArgs[AppDefs.CommandLineOptions.DebugThrowException] != null) { throw new Exception(AppDefs.CommandLineOptions.DebugThrowException); } m_formMain = new MainForm(); Application.Run(m_formMain); #else try { if (m_cmdLineArgs[AppDefs.CommandLineOptions.DebugThrowException] != null) { throw new Exception(AppDefs.CommandLineOptions.DebugThrowException); } m_formMain = new MainForm(); Application.Run(m_formMain); } catch (Exception exPrg) { // Catch message box exception; // https://sourceforge.net/p/keepass/patches/86/ try { MessageService.ShowFatal(exPrg); } catch (Exception) { Console.Error.WriteLine(exPrg.ToString()); } } #endif Application.RemoveMessageFilter(cmfx); Debug.Assert(GlobalWindowManager.WindowCount == 0); Debug.Assert(MessageService.CurrentMessageCount == 0); MainCleanUp(); #if DEBUG string strEndWorkDir = WinUtil.GetWorkingDirectory(); Debug.Assert(strEndWorkDir.Equals(strInitialWorkDir, StrUtil.CaseIgnoreCmp)); #endif if (mGlobalNotify != null) { GC.KeepAlive(mGlobalNotify); } // if(mSingleLock != null) { GC.KeepAlive(mSingleLock); } }
// https://www.fileformat.info/tip/microsoft/enter_unicode.htm // https://sourceforge.net/p/keepass/feature-requests/2180/ private bool HandleAltX(KeyEventArgs e, bool bDown) { // Rich text boxes of Windows already support Alt+X if (!NativeLib.IsUnix()) { return(false); } if (!e.Control && e.Alt && (e.KeyCode == Keys.X)) { } else { return(false); } UIUtil.SetHandled(e, true); if (!bDown) { return(true); } try { string strSel = (this.SelectedText ?? string.Empty); int iSel = this.SelectionStart; Debug.Assert(this.SelectionLength == strSel.Length); if (e.Shift) // Character -> code { string strChar = strSel; if (strSel.Length >= 2) // Work with leftmost character { if (char.IsSurrogatePair(strSel, 0)) { strChar = strSel.Substring(0, 2); } else { strChar = strSel.Substring(0, 1); } } else if (strSel.Length == 0) // Work with char. to the left { int p = iSel - 1; string strText = this.Text; if ((p < 0) || (p >= strText.Length)) { return(true); } char ch = strText[p]; if (!char.IsSurrogate(ch)) { strChar = new string(ch, 1); } else if (p >= 1) { if (char.IsSurrogatePair(strText, p - 1)) { strChar = strText.Substring(p - 1, 2); } } } else // strSel.Length == 1 { if (char.IsSurrogate(strSel[0])) { Debug.Assert(false); // Half surrogate return(true); } } if (strChar.Length == 0) { Debug.Assert(false); return(true); } int uc = char.ConvertToUtf32(strChar, 0); string strRep = Convert.ToString(uc, 16).ToUpperInvariant(); if (strSel.Length >= 2) { this.Select(iSel, strChar.Length); } else if (strSel.Length == 0) { this.Select(iSel - strChar.Length, strChar.Length); iSel -= strChar.Length; } this.SelectedText = strRep; this.Select(iSel, strRep.Length); } else // Code -> character { const uint ucMax = 0x10FFFF; // Max. using surrogates const int ccHexMax = 6; // See e.g. WordPad string strHex = strSel; if (strSel.Length == 0) { int p = iSel - 1; string strText = this.Text; while ((p >= 0) && (p < strText.Length)) { char ch = strText[p]; if (((ch >= '0') && (ch <= '9')) || ((ch >= 'a') && (ch <= 'f')) || ((ch >= 'A') && (ch <= 'F'))) { strHex = (new string(ch, 1)) + strHex; if (strHex.Length == ccHexMax) { break; } } else { break; } --p; } } if ((strHex.Length == 0) || !StrUtil.IsHexString(strHex, true)) { return(true); } string strHexTr = strHex.TrimStart('0'); if (strHexTr.Length > ccHexMax) { return(true); } uint uc = Convert.ToUInt32(strHexTr, 16); if (uc > ucMax) { return(true); } string strRep = char.ConvertFromUtf32((int)uc); if (string.IsNullOrEmpty(strRep)) { Debug.Assert(false); return(true); } if (char.IsControl(strRep, 0) && (strRep[0] != '\t')) { return(true); } if (strSel.Length == 0) { this.Select(iSel - strHex.Length, strHex.Length); } this.SelectedText = strRep; } } catch (Exception) { Debug.Assert(false); } return(true); }
public static byte[] ComputeHash() { try // This works always or never { bool bOpened = OpenW(IntPtr.Zero, false); // The following seems to work even without opening the // clipboard, but opening maybe is safer uint u = NativeMethods.GetClipboardSequenceNumber(); if (bOpened) { CloseW(); } if (u == 0) { throw new UnauthorizedAccessException(); } SHA256Managed sha256 = new SHA256Managed(); return(sha256.ComputeHash(MemUtil.UInt32ToBytes(u))); } catch (Exception) { Debug.Assert(false); } if (NativeLib.GetPlatformID() == PlatformID.MacOSX) { string str = GetStringM(); byte[] pbText = StrUtil.Utf8.GetBytes("pb" + str); return((new SHA256Managed()).ComputeHash(pbText)); } if (NativeLib.IsUnix()) { string str = GetStringU(); byte[] pbText = StrUtil.Utf8.GetBytes("pb" + str); return((new SHA256Managed()).ComputeHash(pbText)); } try { MemoryStream ms = new MemoryStream(); byte[] pbPre = StrUtil.Utf8.GetBytes("pb"); ms.Write(pbPre, 0, pbPre.Length); // Prevent empty buffer if (Clipboard.ContainsAudio()) { Stream sAudio = Clipboard.GetAudioStream(); MemUtil.CopyStream(sAudio, ms); sAudio.Close(); } if (Clipboard.ContainsFileDropList()) { StringCollection sc = Clipboard.GetFileDropList(); foreach (string str in sc) { byte[] pbStr = StrUtil.Utf8.GetBytes(str); ms.Write(pbStr, 0, pbStr.Length); } } if (Clipboard.ContainsImage()) { using (Image img = Clipboard.GetImage()) { MemoryStream msImage = new MemoryStream(); img.Save(msImage, ImageFormat.Bmp); byte[] pbImg = msImage.ToArray(); ms.Write(pbImg, 0, pbImg.Length); msImage.Close(); } } if (Clipboard.ContainsText()) { string str = Clipboard.GetText(); byte[] pbText = StrUtil.Utf8.GetBytes(str); ms.Write(pbText, 0, pbText.Length); } byte[] pbData = ms.ToArray(); SHA256Managed sha256 = new SHA256Managed(); byte[] pbHash = sha256.ComputeHash(pbData); ms.Close(); return(pbHash); } catch (Exception) { Debug.Assert(false); } return(null); }
private void OnFormLoad(object sender, EventArgs e) { Debug.Assert(m_atConfig != null); if (m_atConfig == null) { throw new InvalidOperationException(); } Debug.Assert(m_vStringDict != null); if (m_vStringDict == null) { throw new InvalidOperationException(); } GlobalWindowManager.AddWindow(this); m_ctxKeySeq.Attach(m_rbKeySeq, this); m_ctxKeyCodes.Attach(m_rtbPlaceholders, this); if (!m_bEditSequenceOnly) { BannerFactory.CreateBannerEx(this, m_bannerImage, Properties.Resources.B48x48_KCMSystem, KPRes.ConfigureAutoTypeItem, KPRes.ConfigureAutoTypeItemDesc); } else // Edit keystrokes only { BannerFactory.CreateBannerEx(this, m_bannerImage, Properties.Resources.B48x48_KCMSystem, KPRes.ConfigureKeystrokeSeq, KPRes.ConfigureKeystrokeSeqDesc); } this.Icon = Properties.Resources.KeePass; // FontUtil.AssignDefaultBold(m_lblTargetWindow); // FontUtil.AssignDefaultBold(m_rbSeqDefault); // FontUtil.AssignDefaultBold(m_rbSeqCustom); UIUtil.EnableAutoCompletion(m_cmbWindow, false); // m_clrOriginalForeground = m_lblOpenHint.ForeColor; // m_clrOriginalBackground = m_cmbWindow.BackColor; // m_strOriginalWindowHint = m_lblTargetWindowInfo.Text; InitPlaceholdersBox(); string strInitSeq = m_atConfig.DefaultSequence; if (m_iAssocIndex >= 0) { AutoTypeAssociation asInit = m_atConfig.GetAt(m_iAssocIndex); m_cmbWindow.Text = asInit.WindowName; if (!m_bEditSequenceOnly) { strInitSeq = asInit.Sequence; } } else if (m_bEditSequenceOnly) { m_cmbWindow.Text = "(" + KPRes.Default + ")"; } else { strInitSeq = string.Empty; } bool bSetDefault = false; m_bBlockUpdates = true; if (strInitSeq.Length > 0) { m_rbSeqCustom.Checked = true; } else { m_rbSeqDefault.Checked = true; bSetDefault = true; } m_bBlockUpdates = false; if (bSetDefault) { m_rbKeySeq.Text = m_strDefaultSeq; } else { m_rbKeySeq.Text = strInitSeq; } try { if (NativeLib.IsUnix()) { PopulateWindowsListUnix(); } else { PopulateWindowsListWin(); } } catch (Exception) { Debug.Assert(false); } EnableControlsEx(); }
public static void ConfigureProcess() { Debug.Assert(!m_bInitialized); // Configure process before use if (NativeLib.IsUnix()) { return; } // try // { // ConfigurationManager.AppSettings.Set( // "EnableWindowsFormsHighDpiAutoResizing", "true"); // } // catch(Exception) { Debug.Assert(false); } #if DEBUG // Ensure that the .config file enables high DPI features string strExeConfig = WinUtil.GetExecutable() + ".config"; if (File.Exists(strExeConfig)) { string strCM = "System.Configuration.ConfigurationManager, "; strCM += "System.Configuration, Version="; strCM += Environment.Version.Major.ToString() + ".0.0.0, "; strCM += "Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; Type tCM = Type.GetType(strCM, false); if (tCM != null) { PropertyInfo pi = tCM.GetProperty("AppSettings", (BindingFlags.Public | BindingFlags.Static)); if (pi != null) { NameValueCollection nvc = (pi.GetValue(null, null) as NameValueCollection); if (nvc != null) { Debug.Assert(string.Equals(nvc.Get( "EnableWindowsFormsHighDpiAutoResizing"), "true", StrUtil.CaseIgnoreCmp)); } else { Debug.Assert(false); } } else { Debug.Assert(false); } } else { Debug.Assert(false); } // Assembly should be loaded } #endif try { // SetProcessDPIAware is obsolete; use // SetProcessDpiAwareness on Windows 10 and higher if (WinUtil.IsAtLeastWindows10) // 8.1 partially { if (NativeMethods.SetProcessDpiAwareness( NativeMethods.ProcessDpiAwareness.SystemAware) < 0) { Debug.Assert(false); } } else if (WinUtil.IsAtLeastWindowsVista) { if (!NativeMethods.SetProcessDPIAware()) { Debug.Assert(false); } } } catch (Exception) { Debug.Assert(false); } }
/* private static void OnHotKey(string strKey, IntPtr lpUserData) * { * if(string.IsNullOrEmpty(strKey)) return; * if(strKey.IndexOf(@"<Release>", StrUtil.CaseIgnoreCmp) >= 0) return; * * if(m_fRecvWnd != null) * { * MainForm mf = (m_fRecvWnd as MainForm); * if(mf == null) { Debug.Assert(false); return; } * * Keys k = EggAccStringToKeys(strKey); * foreach(KeyValuePair<int, Keys> kvp in m_vRegKeys) * { * if(kvp.Value == k) mf.HandleHotKey(kvp.Key); * } * } * else { Debug.Assert(false); } * } * * private static Keys EggAccStringToKeys(string strKey) * { * if(string.IsNullOrEmpty(strKey)) return Keys.None; * * Keys k = Keys.None; * * if(strKey.IndexOf(@"<Alt>", StrUtil.CaseIgnoreCmp) >= 0) * k |= Keys.Alt; * if((strKey.IndexOf(@"<Ctl>", StrUtil.CaseIgnoreCmp) >= 0) || * (strKey.IndexOf(@"<Ctrl>", StrUtil.CaseIgnoreCmp) >= 0) || * (strKey.IndexOf(@"<Control>", StrUtil.CaseIgnoreCmp) >= 0)) * k |= Keys.Control; * if((strKey.IndexOf(@"<Shft>", StrUtil.CaseIgnoreCmp) >= 0) || * (strKey.IndexOf(@"<Shift>", StrUtil.CaseIgnoreCmp) >= 0)) * k |= Keys.Shift; * * string strKeyCode = strKey; * while(strKeyCode.IndexOf('<') >= 0) * { * int nStart = strKeyCode.IndexOf('<'); * int nEnd = strKeyCode.IndexOf('>'); * if((nStart < 0) || (nEnd < 0) || (nEnd <= nStart)) { Debug.Assert(false); break; } * * strKeyCode = strKeyCode.Remove(nStart, nEnd - nStart + 1); * } * strKeyCode = strKeyCode.Trim(); * * try { k |= (Keys)Enum.Parse(typeof(Keys), strKeyCode, true); } * catch(Exception) { Debug.Assert(false); } * * return k; * } * * private static string EggAccKeysToString(Keys k) * { * StringBuilder sb = new StringBuilder(); * * if((k & Keys.Shift) != Keys.None) sb.Append(@"<Shift>"); * if((k & Keys.Control) != Keys.None) sb.Append(@"<Control>"); * if((k & Keys.Alt) != Keys.None) sb.Append(@"<Alt>"); * * sb.Append((k & Keys.KeyCode).ToString()); * return sb.ToString(); * } */ internal static void CheckCtrlAltA(Form fParent) { try { if (!Program.Config.Integration.CheckHotKeys) { return; } if (NativeLib.IsUnix()) { return; } // Check for a conflict only in the very specific case of // Ctrl+Alt+A; in all other cases we assume that the user // is aware of a possible conflict and intentionally wants // to override any system key combination if (Program.Config.Integration.HotKeyGlobalAutoType != (long)(Keys.Control | Keys.Alt | Keys.A)) { return; } // Check for a conflict only on Polish systems; other // languages typically don't use Ctrl+Alt+A frequently // and a conflict warning would just be confusing for // most users IntPtr hKL = NativeMethods.GetKeyboardLayout(0); ushort uLangID = (ushort)(hKL.ToInt64() & 0xFFFFL); ushort uPriLangID = NativeMethods.GetPrimaryLangID(uLangID); if (uPriLangID != NativeMethods.LANG_POLISH) { return; } int vk = (int)Keys.A; // We actually check for RAlt (which maps to Ctrl+Alt) // instead of LCtrl+LAlt byte[] pbState = new byte[256]; pbState[NativeMethods.VK_CONTROL] = 0x80; pbState[NativeMethods.VK_MENU] = 0x80; pbState[NativeMethods.VK_RMENU] = 0x80; pbState[NativeMethods.VK_NUMLOCK] = 0x01; // Toggled // pbState[vk] = 0x80; string strUni = NativeMethods.ToUnicode3(vk, pbState, IntPtr.Zero); if (string.IsNullOrEmpty(strUni)) { return; } if (strUni.EndsWith("a") || strUni.EndsWith("A")) { return; } if (char.IsControl(strUni, 0)) { Debug.Assert(false); strUni = "?"; } string str = KPRes.CtrlAltAConflict.Replace(@"{PARAM}", strUni) + MessageService.NewParagraph + KPRes.CtrlAltAConflictHint; VistaTaskDialog dlg = new VistaTaskDialog(); dlg.AddButton((int)DialogResult.Cancel, KPRes.Ok, null); dlg.CommandLinks = false; dlg.Content = str; dlg.DefaultButtonID = (int)DialogResult.Cancel; dlg.MainInstruction = KPRes.KeyboardKeyCtrl + "+" + KPRes.KeyboardKeyAlt + "+A - " + KPRes.Warning; dlg.SetIcon(VtdIcon.Warning); dlg.VerificationText = KPRes.DialogNoShowAgain; dlg.WindowTitle = PwDefs.ShortProductName; if (dlg.ShowDialog(fParent)) { if (dlg.ResultVerificationChecked) { Program.Config.Integration.CheckHotKeys = false; } } else { MessageService.ShowWarning(str); } } catch (Exception) { Debug.Assert(false); } }
public static bool Copy(string strToCopy, bool bSprCompile, bool bIsEntryInfo, PwEntry peEntryInfo, PwDatabase pwReferenceSource, IntPtr hOwner) { if (strToCopy == null) { throw new ArgumentNullException("strToCopy"); } if (strToCopy.Length == 0) { Clear(); return(true); } if (bIsEntryInfo && !AppPolicy.Try(AppPolicyId.CopyToClipboard)) { return(false); } string strData = strToCopy; if (bSprCompile) { strData = SprEngine.Compile(strData, new SprContext( peEntryInfo, pwReferenceSource, SprCompileFlags.All)); } try { // if(SetStringUwp(strData)) { } else if (!NativeLib.IsUnix()) // Windows { if (!OpenW(hOwner, true)) { throw new InvalidOperationException(); } bool bFailed = false; if (!AttachIgnoreFormatsW()) { bFailed = true; } if (!SetDataW(null, strData, null)) { bFailed = true; } CloseW(); if (bFailed) { return(false); } } else if (NativeLib.GetPlatformID() == PlatformID.MacOSX) { SetStringM(strData); } else if (NativeLib.IsUnix()) { SetStringU(strData); } else { Debug.Assert(false); Clipboard.SetText(strData); } } catch (Exception) { Debug.Assert(false); return(false); } g_pbDataHash = HashString(strData); if (peEntryInfo != null) { peEntryInfo.Touch(false); } if (bIsEntryInfo) { Program.TriggerSystem.RaiseEvent(EcasEventIDs.CopiedEntryInfo, EcasProperty.Text, strData); } // SprEngine.Compile might have modified the database MainForm mf = Program.MainForm; if ((mf != null) && bSprCompile) { mf.RefreshEntriesList(); mf.UpdateUI(false, null, false, null, false, null, false); } return(true); }
public static Image GetImageForPath(string strPath, Size?osz, bool bAllowCache, bool bNewImageObject) { if (strPath == null) { Debug.Assert(false); strPath = string.Empty; } Size sz = GetSizeOrSmall(osz); Image img = null; bool bImgIsNew = false; string strKey = GetCacheItemKey(FiTypePath, strPath, sz); if (bAllowCache && g_dCache.TryGetValue(strKey, out img)) { if (bNewImageObject) { img = (img.Clone() as Image); } return(img); } Debug.Assert(img == null); if (strPath.Length == 0) { img = Properties.Resources.B16x16_Binary; bImgIsNew = false; } try { if ((img == null) && !NativeLib.IsUnix()) { string strDisplayName; NativeMethods.SHGetFileInfo(strPath, sz.Width, sz.Height, out img, out strDisplayName); bImgIsNew = true; } } catch (Exception) { Debug.Assert(false); } if ((img == null) && !MonoWorkarounds.IsRequired(100003)) { img = UIUtil.GetFileIcon(strPath, sz.Width, sz.Height); bImgIsNew = true; } if (img == null) { BinaryDataClass bdc = BinaryDataClassifier.ClassifyUrl(strPath); if ((bdc == BinaryDataClass.Text) || (bdc == BinaryDataClass.RichText)) { img = Properties.Resources.B16x16_ASCII; } else if (bdc == BinaryDataClass.Image) { img = Properties.Resources.B16x16_Spreadsheet; } else if (bdc == BinaryDataClass.WebDocument) { img = Properties.Resources.B16x16_HTML; } else if (strPath.EndsWith(".exe", StrUtil.CaseIgnoreCmp)) { img = Properties.Resources.B16x16_Make_KDevelop; } else { img = Properties.Resources.B16x16_Binary; } bImgIsNew = false; } if (img == null) { Debug.Assert(false); return(null); } if ((img.Width != sz.Width) || (img.Height != sz.Height)) { Image imgSc = GfxUtil.ScaleImage(img, sz.Width, sz.Height, ScaleTransformFlags.UIIcon); if (bImgIsNew) { img.Dispose(); } img = imgSc; } if (bAllowCache) { g_dCache[strKey] = img; } if (bNewImageObject && (bAllowCache || !bImgIsNew)) { img = (img.Clone() as Image); } return(img); }
static WinUtil() { if (NativeLib.IsUnix()) { return; } OperatingSystem os = Environment.OSVersion; Version v = os.Version; m_bIsWindows9x = (os.Platform == PlatformID.Win32Windows); m_bIsWindows2000 = ((v.Major == 5) && (v.Minor == 0)); m_bIsWindowsXP = ((v.Major == 5) && (v.Minor == 1)); m_bIsAtLeastWindows2000 = (v.Major >= 5); m_bIsAtLeastWindowsVista = (v.Major >= 6); m_bIsAtLeastWindows7 = ((v.Major >= 7) || ((v.Major == 6) && (v.Minor >= 1))); m_bIsAtLeastWindows8 = ((v.Major >= 7) || ((v.Major == 6) && (v.Minor >= 2))); // Environment.OSVersion is reliable only up to version 6.2; // https://msdn.microsoft.com/library/windows/desktop/ms724832.aspx RegistryKey rk = null; try { rk = Registry.LocalMachine.OpenSubKey( "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", false); if (rk != null) { string str = rk.GetValue("CurrentMajorVersionNumber", string.Empty).ToString(); uint u; if (uint.TryParse(str, out u)) { m_bIsAtLeastWindows10 = (u >= 10); } else { Debug.Assert(string.IsNullOrEmpty(str)); } } else { Debug.Assert(false); } } catch (Exception) { Debug.Assert(false); } finally { if (rk != null) { rk.Close(); } } try { string strDir = UrlUtil.GetFileDirectory(GetExecutable(), false, false); if (strDir.IndexOf("\\WindowsApps\\", StrUtil.CaseIgnoreCmp) >= 0) { Regex rx = new Regex("\\\\WindowsApps\\\\.*?_\\d+(\\.\\d+)*_", RegexOptions.IgnoreCase); m_bIsAppX = rx.IsMatch(strDir); } else { Debug.Assert(!m_bIsAppX); } // No AppX by default } catch (Exception) { Debug.Assert(false); } }
private void OnFormLoad(object sender, EventArgs e) { Debug.Assert(m_atConfig != null); if(m_atConfig == null) throw new InvalidOperationException(); Debug.Assert(m_vStringDict != null); if(m_vStringDict == null) throw new InvalidOperationException(); GlobalWindowManager.AddWindow(this); m_ctxKeySeq.Attach(m_rbKeySeq, this); m_ctxKeyCodes.Attach(m_rtbPlaceholders, this); if(!m_bEditSequenceOnly) { BannerFactory.CreateBannerEx(this, m_bannerImage, Properties.Resources.B48x48_KCMSystem, KPRes.ConfigureAutoTypeItem, KPRes.ConfigureAutoTypeItemDesc); } else // Edit keystrokes only { BannerFactory.CreateBannerEx(this, m_bannerImage, Properties.Resources.B48x48_KCMSystem, KPRes.ConfigureKeystrokeSeq, KPRes.ConfigureKeystrokeSeqDesc); } this.Icon = AppIcons.Default; // FontUtil.AssignDefaultBold(m_lblTargetWindow); // FontUtil.AssignDefaultBold(m_rbSeqDefault); // FontUtil.AssignDefaultBold(m_rbSeqCustom); UIUtil.EnableAutoCompletion(m_cmbWindow, false); // m_clrOriginalForeground = m_lblOpenHint.ForeColor; // m_clrOriginalBackground = m_cmbWindow.BackColor; // m_strOriginalWindowHint = m_lblTargetWindowInfo.Text; bool bRtl = Program.Translation.Properties.RightToLeft; if(bRtl) { // https://sourceforge.net/p/keepass/discussion/329220/thread/f98dece5/ m_rbKeySeq.RightToLeft = RightToLeft.No; m_rtbPlaceholders.RightToLeft = RightToLeft.No; } InitPlaceholdersBox(bRtl); string strInitSeq = m_atConfig.DefaultSequence; if(m_iAssocIndex >= 0) { AutoTypeAssociation asInit = m_atConfig.GetAt(m_iAssocIndex); m_cmbWindow.Text = asInit.WindowName; if(!m_bEditSequenceOnly) strInitSeq = asInit.Sequence; } else if(m_bEditSequenceOnly) m_cmbWindow.Text = "(" + KPRes.Default + ")"; else strInitSeq = string.Empty; bool bSetDefault = false; m_bBlockUpdates = true; if(strInitSeq.Length > 0) m_rbSeqCustom.Checked = true; else { m_rbSeqDefault.Checked = true; bSetDefault = true; } m_bBlockUpdates = false; if(bSetDefault) m_rbKeySeq.Text = m_strDefaultSeq; else m_rbKeySeq.Text = strInitSeq; try { if(NativeLib.IsUnix()) PopulateWindowsListUnix(); else PopulateWindowsListWin(); } catch(Exception) { Debug.Assert(false); } EnableControlsEx(); }
public static void Main(string[] args) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.DoEvents(); // Required #if DEBUG string strInitialWorkDir = WinUtil.GetWorkingDirectory(); #endif if (!CommonInit()) { CommonTerminate(); return; } if (m_appConfig.Application.Start.PluginCacheClearOnce) { PlgxCache.Clear(); m_appConfig.Application.Start.PluginCacheClearOnce = false; AppConfigSerializer.Save(Program.Config); } m_cmdLineArgs = new CommandLineArgs(args); if (m_cmdLineArgs[AppDefs.CommandLineOptions.FileExtRegister] != null) { ShellUtil.RegisterExtension(AppDefs.FileExtension.FileExt, AppDefs.FileExtension.ExtId, KPRes.FileExtName, WinUtil.GetExecutable(), PwDefs.ShortProductName, false); MainCleanUp(); return; } else if (m_cmdLineArgs[AppDefs.CommandLineOptions.FileExtUnregister] != null) { ShellUtil.UnregisterExtension(AppDefs.FileExtension.FileExt, AppDefs.FileExtension.ExtId); MainCleanUp(); return; } else if (m_cmdLineArgs[AppDefs.CommandLineOptions.PreLoad] != null) { // All important .NET assemblies are in memory now already try { SelfTest.Perform(); } catch (Exception) { Debug.Assert(false); } MainCleanUp(); return; } /* else if(m_cmdLineArgs[AppDefs.CommandLineOptions.PreLoadRegister] != null) * { * string strPreLoadPath = WinUtil.GetExecutable().Trim(); * if(strPreLoadPath.StartsWith("\"") == false) * strPreLoadPath = "\"" + strPreLoadPath + "\""; * ShellUtil.RegisterPreLoad(AppDefs.PreLoadName, strPreLoadPath, * @"--" + AppDefs.CommandLineOptions.PreLoad, true); * MainCleanUp(); * return; * } * else if(m_cmdLineArgs[AppDefs.CommandLineOptions.PreLoadUnregister] != null) * { * ShellUtil.RegisterPreLoad(AppDefs.PreLoadName, string.Empty, * string.Empty, false); * MainCleanUp(); * return; * } */ else if ((m_cmdLineArgs[AppDefs.CommandLineOptions.Help] != null) || (m_cmdLineArgs[AppDefs.CommandLineOptions.HelpLong] != null)) { AppHelp.ShowHelp(AppDefs.HelpTopics.CommandLine, null); MainCleanUp(); return; } else if (m_cmdLineArgs[AppDefs.CommandLineOptions.ConfigSetUrlOverride] != null) { Program.Config.Integration.UrlOverride = m_cmdLineArgs[ AppDefs.CommandLineOptions.ConfigSetUrlOverride]; AppConfigSerializer.Save(Program.Config); MainCleanUp(); return; } else if (m_cmdLineArgs[AppDefs.CommandLineOptions.ConfigClearUrlOverride] != null) { Program.Config.Integration.UrlOverride = string.Empty; AppConfigSerializer.Save(Program.Config); MainCleanUp(); return; } else if (m_cmdLineArgs[AppDefs.CommandLineOptions.ConfigGetUrlOverride] != null) { try { string strFileOut = UrlUtil.EnsureTerminatingSeparator( UrlUtil.GetTempPath(), false) + "KeePass_UrlOverride.tmp"; string strContent = ("[KeePass]\r\nKeeURLOverride=" + Program.Config.Integration.UrlOverride + "\r\n"); File.WriteAllText(strFileOut, strContent); } catch (Exception) { Debug.Assert(false); } MainCleanUp(); return; } else if (m_cmdLineArgs[AppDefs.CommandLineOptions.ConfigSetLanguageFile] != null) { Program.Config.Application.LanguageFile = m_cmdLineArgs[ AppDefs.CommandLineOptions.ConfigSetLanguageFile]; AppConfigSerializer.Save(Program.Config); MainCleanUp(); return; } else if (m_cmdLineArgs[AppDefs.CommandLineOptions.PlgxCreate] != null) { PlgxPlugin.CreateFromCommandLine(); MainCleanUp(); return; } else if (m_cmdLineArgs[AppDefs.CommandLineOptions.PlgxCreateInfo] != null) { PlgxPlugin.CreateInfoFile(m_cmdLineArgs.FileName); MainCleanUp(); return; } else if (m_cmdLineArgs[AppDefs.CommandLineOptions.ShowAssemblyInfo] != null) { MessageService.ShowInfo(Assembly.GetExecutingAssembly().ToString()); MainCleanUp(); return; } else if (m_cmdLineArgs[AppDefs.CommandLineOptions.MakeXmlSerializerEx] != null) { XmlSerializerEx.GenerateSerializers(m_cmdLineArgs); MainCleanUp(); return; } // #if (DEBUG && !KeePassLibSD) // else if(m_cmdLineArgs[AppDefs.CommandLineOptions.MakePopularPasswordTable] != null) // { // PopularPasswords.MakeList(); // MainCleanUp(); // return; // } // #endif try { m_nAppMessage = NativeMethods.RegisterWindowMessage(m_strWndMsgID); } catch (Exception) { Debug.Assert(NativeLib.IsUnix()); } if (m_cmdLineArgs[AppDefs.CommandLineOptions.ExitAll] != null) { BroadcastAppMessageAndCleanUp(AppMessage.Exit); return; } else if (m_cmdLineArgs[AppDefs.CommandLineOptions.AutoType] != null) { BroadcastAppMessageAndCleanUp(AppMessage.AutoType); return; } else if (m_cmdLineArgs[AppDefs.CommandLineOptions.AutoTypeSelected] != null) { BroadcastAppMessageAndCleanUp(AppMessage.AutoTypeSelected); return; } else if (m_cmdLineArgs[AppDefs.CommandLineOptions.OpenEntryUrl] != null) { string strEntryUuid = m_cmdLineArgs[AppDefs.CommandLineOptions.Uuid]; if (!string.IsNullOrEmpty(strEntryUuid)) { IpcParamEx ipUrl = new IpcParamEx(IpcUtilEx.CmdOpenEntryUrl, strEntryUuid, null, null, null, null); IpcUtilEx.SendGlobalMessage(ipUrl); } MainCleanUp(); return; } else if (m_cmdLineArgs[AppDefs.CommandLineOptions.LockAll] != null) { BroadcastAppMessageAndCleanUp(AppMessage.Lock); return; } else if (m_cmdLineArgs[AppDefs.CommandLineOptions.UnlockAll] != null) { BroadcastAppMessageAndCleanUp(AppMessage.Unlock); return; } // Mutex mSingleLock = TrySingleInstanceLock(AppDefs.MutexName, true); bool bSingleLock = GlobalMutexPool.CreateMutex(AppDefs.MutexName, true); // if((mSingleLock == null) && m_appConfig.Integration.LimitToSingleInstance) if (!bSingleLock && m_appConfig.Integration.LimitToSingleInstance) { ActivatePreviousInstance(args); MainCleanUp(); return; } Mutex mGlobalNotify = TryGlobalInstanceNotify(AppDefs.MutexNameGlobal); AutoType.InitStatic(); UserActivityNotifyFilter nfActivity = new UserActivityNotifyFilter(); Application.AddMessageFilter(nfActivity); #if DEBUG if (m_cmdLineArgs[AppDefs.CommandLineOptions.DebugThrowException] != null) { throw new Exception(AppDefs.CommandLineOptions.DebugThrowException); } m_formMain = new MainForm(); Application.Run(m_formMain); #else try { if (m_cmdLineArgs[AppDefs.CommandLineOptions.DebugThrowException] != null) { throw new Exception(AppDefs.CommandLineOptions.DebugThrowException); } m_formMain = new MainForm(); Application.Run(m_formMain); } catch (Exception exPrg) { // Catch message box exception; // https://sourceforge.net/p/keepass/patches/86/ try { MessageService.ShowFatal(exPrg); } catch (Exception) { Console.Error.WriteLine(exPrg.ToString()); } } #endif Application.RemoveMessageFilter(nfActivity); Debug.Assert(GlobalWindowManager.WindowCount == 0); Debug.Assert(MessageService.CurrentMessageCount == 0); MainCleanUp(); #if DEBUG string strEndWorkDir = WinUtil.GetWorkingDirectory(); Debug.Assert(strEndWorkDir.Equals(strInitialWorkDir, StrUtil.CaseIgnoreCmp)); #endif if (mGlobalNotify != null) { GC.KeepAlive(mGlobalNotify); } // if(mSingleLock != null) { GC.KeepAlive(mSingleLock); } }
public static bool PerformIntoCurrentWindow(PwEntry pe, PwDatabase pdContext, string strSeq) { if (pe == null) { Debug.Assert(false); return(false); } if (!pe.GetAutoTypeEnabled()) { return(false); } if (!AppPolicy.Try(AppPolicyId.AutoTypeWithoutContext)) { return(false); } Thread.Sleep(TargetActivationDelay); IntPtr hWnd; string strWindow; try { NativeMethods.GetForegroundWindowInfo(out hWnd, out strWindow, true); } catch (Exception) { hWnd = IntPtr.Zero; strWindow = null; } if (!NativeLib.IsUnix()) { if (strWindow == null) { Debug.Assert(false); return(false); } } else { strWindow = string.Empty; } if (strSeq == null) { SequenceQueriesEventArgs evQueries = GetSequencesForWindowBegin( hWnd, strWindow); List <string> lSeq = GetSequencesForWindow(pe, hWnd, strWindow, pdContext, evQueries.EventID); GetSequencesForWindowEnd(evQueries); if (lSeq.Count == 0) { strSeq = pe.GetAutoTypeSequence(); } else { strSeq = lSeq[0]; } } AutoTypeCtx ctx = new AutoTypeCtx(strSeq, pe, pdContext); return(AutoType.PerformInternal(ctx, strWindow)); }
private void OnFormLoad(object sender, EventArgs e) { // Can be invoked by tray command; don't use CenterParent Debug.Assert(this.StartPosition == FormStartPosition.CenterScreen); GlobalWindowManager.AddWindow(this); this.Icon = Properties.Resources.KeePass; Debug.Assert(m_ilIcons != null); if (m_ilIcons != null) { m_tabMain.ImageList = m_ilIcons; m_tabSecurity.ImageIndex = (int)PwIcon.TerminalEncrypted; m_tabPolicy.ImageIndex = (int)PwIcon.List; m_tabGui.ImageIndex = (int)PwIcon.Screen; m_tabIntegration.ImageIndex = (int)PwIcon.Console; m_tabAdvanced.ImageIndex = (int)PwIcon.ClipboardReady; } uint uTab = Program.Config.Defaults.OptionsTabIndex; if (uTab < (uint)m_tabMain.TabPages.Count) { m_tabMain.SelectedTab = m_tabMain.TabPages[(int)uTab]; } m_aceUrlSchemeOverrides = Program.Config.Integration.UrlSchemeOverrides.CloneDeep(); m_cmbBannerStyle.Items.Add("(" + KPRes.CurrentStyle + ")"); m_cmbBannerStyle.Items.Add("WinXP Login"); m_cmbBannerStyle.Items.Add("WinVista Black"); m_cmbBannerStyle.Items.Add("KeePass Win32"); m_cmbBannerStyle.Items.Add("Blue Carbon"); CreateDialogBanner(BannerStyle.Default); // Default forces generation m_cmbBannerStyle.SelectedIndex = (int)BannerStyle.Default; if ((BannerFactory.CustomGenerator != null) || AppConfigEx.IsOptionEnforced(Program.Config.UI, "BannerStyle")) { m_lblBannerStyle.Enabled = false; m_cmbBannerStyle.Enabled = false; } int nWidth = m_lvPolicy.ClientRectangle.Width - UIUtil.GetVScrollBarWidth() - 1; m_lvPolicy.Columns.Add(KPRes.Feature, (nWidth * 10) / 29); m_lvPolicy.Columns.Add(KPRes.Description, (nWidth * 19) / 29); m_hkGlobalAutoType = HotKeyControlEx.ReplaceTextBox(m_grpHotKeys, m_tbGlobalAutoType, true); m_hkSelectedAutoType = HotKeyControlEx.ReplaceTextBox(m_grpHotKeys, m_tbSelAutoTypeHotKey, true); m_hkShowWindow = HotKeyControlEx.ReplaceTextBox(m_grpHotKeys, m_tbShowWindowHotKey, true); if (!NativeLib.IsUnix()) { UIUtil.SetShield(m_btnFileExtCreate, true); UIUtil.SetShield(m_btnFileExtRemove, true); m_linkHotKeyHelp.Visible = false; } else // Unix { Program.Config.Integration.HotKeyGlobalAutoType = (ulong)Keys.None; Program.Config.Integration.HotKeySelectedAutoType = (ulong)Keys.None; Program.Config.Integration.HotKeyShowWindow = (ulong)Keys.None; m_hkGlobalAutoType.Enabled = m_hkSelectedAutoType.Enabled = m_hkShowWindow.Enabled = false; m_btnFileExtCreate.Enabled = m_btnFileExtRemove.Enabled = false; m_cbAutoRun.Enabled = false; } UIUtil.SetExplorerTheme(m_lvSecurityOptions, false); UIUtil.SetExplorerTheme(m_lvPolicy, false); UIUtil.SetExplorerTheme(m_lvGuiOptions, false); UIUtil.SetExplorerTheme(m_lvAdvanced, false); AppConfigEx.ClearXmlPathCache(); LoadOptions(); // if(Program.Config.Meta.IsEnforcedConfiguration) // m_lvPolicy.Enabled = false; UpdateUIState(); }
public static bool Copy(byte[] pbToCopy, string strFormat, bool bEncode, bool bIsEntryInfo, IntPtr hOwner) { Debug.Assert(pbToCopy != null); if (pbToCopy == null) { throw new ArgumentNullException("pbToCopy"); } if (bIsEntryInfo && !AppPolicy.Try(AppPolicyId.CopyToClipboard)) { return(false); } string strEnc = null; try { if (bEncode || NativeLib.IsUnix()) { strEnc = StrUtil.DataToDataUri(pbToCopy, ClipFmtToMimeType(strFormat)); } if (!NativeLib.IsUnix()) // Windows { if (!OpenW(hOwner, true)) { throw new InvalidOperationException(); } uint uFormat = NativeMethods.RegisterClipboardFormat(strFormat); bool bFailed = false; if (!AttachIgnoreFormatW()) { bFailed = true; } if (!bEncode) { if (!SetDataW(uFormat, pbToCopy)) { bFailed = true; } } else // Encode { if (!SetDataW(uFormat, strEnc, false)) { bFailed = true; } } CloseW(); if (bFailed) { return(false); } } else if (NativeLib.GetPlatformID() == PlatformID.MacOSX) { SetStringM(strEnc); } else if (NativeLib.IsUnix()) { SetStringU(strEnc); } // else // Managed, no encoding // { // Clear(); // DataObject doData = CreateProtectedDataObject(strFormat, pbToCopy); // Clipboard.SetDataObject(doData); // } } catch (Exception) { Debug.Assert(false); return(false); } m_strFormat = strFormat; m_bEncoded = (strEnc != null); SHA256Managed sha256 = new SHA256Managed(); // if(strEnc != null) // m_pbDataHash32 = sha256.ComputeHash(StrUtil.Utf8.GetBytes(strEnc)); // else m_pbDataHash32 = sha256.ComputeHash(pbToCopy); RaiseCopyEvent(bIsEntryInfo, string.Empty); return(true); }
private void OnFormLoad(object sender, EventArgs e) { // Can be invoked by tray command; don't use CenterParent Debug.Assert(this.StartPosition == FormStartPosition.CenterScreen); // When multiline is enabled, tabs added by plugins can result // in multiple tab rows, cropping the tab content at the bottom; // https://sourceforge.net/p/keepass/discussion/329220/thread/a17a2734/ Debug.Assert(!m_tabMain.Multiline); GlobalWindowManager.AddWindow(this); this.Icon = AppIcons.Default; Debug.Assert(m_ilIcons != null); if (m_ilIcons != null) { m_tabMain.ImageList = m_ilIcons; m_tabSecurity.ImageIndex = (int)PwIcon.TerminalEncrypted; m_tabPolicy.ImageIndex = (int)PwIcon.List; m_tabGui.ImageIndex = (int)PwIcon.Screen; m_tabIntegration.ImageIndex = (int)PwIcon.Console; m_tabAdvanced.ImageIndex = (int)PwIcon.ClipboardReady; } uint uTab = Program.Config.Defaults.OptionsTabIndex; if (uTab < (uint)m_tabMain.TabPages.Count) { m_tabMain.SelectedTab = m_tabMain.TabPages[(int)uTab]; } m_aceUrlSchemeOverrides = Program.Config.Integration.UrlSchemeOverrides.CloneDeep(); m_strUrlOverrideAll = Program.Config.Integration.UrlOverride; Debug.Assert(!m_cmbMenuStyle.Sorted); m_cmbMenuStyle.Items.Add(KPRes.Auto + " (" + KPRes.Recommended + ")"); m_cmbMenuStyle.Items.Add(new string('-', 24)); int nTsrs = 2, iTsrSel = 0, nSuffixes = 0; foreach (TsrFactory fTsr in TsrPool.Factories) { string strSuffix = string.Empty; if (!fTsr.IsSupported()) { strSuffix = " (" + KPRes.IncompatibleEnv + ")"; ++nSuffixes; } string strUuid = Convert.ToBase64String(fTsr.Uuid.UuidBytes); if (Program.Config.UI.ToolStripRenderer == strUuid) { iTsrSel = nTsrs; } m_cmbMenuStyle.Items.Add((fTsr.Name ?? string.Empty) + strSuffix); m_dTsrUuids[nTsrs] = strUuid; ++nTsrs; } Debug.Assert(m_cmbMenuStyle.Items.Count == nTsrs); m_cmbMenuStyle.SelectedIndex = iTsrSel; if (nSuffixes > 0) { m_cmbMenuStyle.DropDownWidth = m_cmbMenuStyle.Width * 2; } if (AppConfigEx.IsOptionEnforced(Program.Config.UI, "ToolStripRenderer")) { m_lblMenuStyle.Enabled = false; m_cmbMenuStyle.Enabled = false; } Debug.Assert(!m_cmbBannerStyle.Sorted); m_cmbBannerStyle.Items.Add("(" + KPRes.CurrentStyle + ")"); m_cmbBannerStyle.Items.Add("Windows XP Login"); m_cmbBannerStyle.Items.Add("Windows Vista Black"); m_cmbBannerStyle.Items.Add("KeePass Win32"); m_cmbBannerStyle.Items.Add("Blue Carbon"); CreateDialogBanner(BannerStyle.Default); // Default forces generation m_cmbBannerStyle.SelectedIndex = (int)BannerStyle.Default; if ((BannerFactory.CustomGenerator != null) || AppConfigEx.IsOptionEnforced(Program.Config.UI, "BannerStyle")) { m_lblBannerStyle.Enabled = false; m_cmbBannerStyle.Enabled = false; } int nWidth = m_lvPolicy.ClientSize.Width - UIUtil.GetVScrollBarWidth(); m_lvPolicy.Columns.Add(KPRes.Feature, (nWidth * 10) / 29); m_lvPolicy.Columns.Add(KPRes.Description, (nWidth * 19) / 29); m_hkGlobalAutoType = HotKeyControlEx.ReplaceTextBox(m_grpHotKeys, m_tbGlobalAutoType, false); m_hkSelectedAutoType = HotKeyControlEx.ReplaceTextBox(m_grpHotKeys, m_tbSelAutoTypeHotKey, false); m_hkShowWindow = HotKeyControlEx.ReplaceTextBox(m_grpHotKeys, m_tbShowWindowHotKey, false); if (!NativeLib.IsUnix()) { UIUtil.SetShield(m_btnFileExtCreate, true); UIUtil.SetShield(m_btnFileExtRemove, true); m_linkHotKeyHelp.Visible = false; } else // Unix { m_hkGlobalAutoType.TextNone = KPRes.External; m_hkSelectedAutoType.TextNone = KPRes.External; m_hkShowWindow.TextNone = KPRes.External; m_hkGlobalAutoType.Enabled = m_hkSelectedAutoType.Enabled = m_hkShowWindow.Enabled = false; m_btnFileExtCreate.Enabled = m_btnFileExtRemove.Enabled = false; m_cbAutoRun.Enabled = false; } UIUtil.SetExplorerTheme(m_lvSecurityOptions, false); UIUtil.SetExplorerTheme(m_lvPolicy, false); UIUtil.SetExplorerTheme(m_lvGuiOptions, false); UIUtil.SetExplorerTheme(m_lvAdvanced, false); AppConfigEx.ClearXmlPathCache(); LoadOptions(); // if(Program.Config.Meta.IsEnforcedConfiguration) // m_lvPolicy.Enabled = false; UpdateUIState(); }
public static bool Copy(string strToCopy, bool bSprCompile, bool bIsEntryInfo, PwEntry peEntryInfo, PwDatabase pwReferenceSource, IntPtr hOwner) { if (strToCopy == null) { throw new ArgumentNullException("strToCopy"); } if (bIsEntryInfo && !AppPolicy.Try(AppPolicyId.CopyToClipboard)) { return(false); } string strData = (bSprCompile ? SprEngine.Compile(strToCopy, new SprContext(peEntryInfo, pwReferenceSource, SprCompileFlags.All)) : strToCopy); try { if (!NativeLib.IsUnix()) // Windows { if (!OpenW(hOwner, true)) { throw new InvalidOperationException(); } bool bFailed = false; if (!AttachIgnoreFormatW()) { bFailed = true; } if (!SetDataW(null, strData, null)) { bFailed = true; } CloseW(); if (bFailed) { return(false); } } else if (NativeLib.GetPlatformID() == PlatformID.MacOSX) { SetStringM(strData); } else if (NativeLib.IsUnix()) { SetStringU(strData); } // else // Managed // { // Clear(); // DataObject doData = CreateProtectedDataObject(strData); // Clipboard.SetDataObject(doData); // } } catch (Exception) { Debug.Assert(false); return(false); } m_strFormat = null; byte[] pbUtf8 = StrUtil.Utf8.GetBytes(strData); SHA256Managed sha256 = new SHA256Managed(); m_pbDataHash32 = sha256.ComputeHash(pbUtf8); RaiseCopyEvent(bIsEntryInfo, strData); if (peEntryInfo != null) { peEntryInfo.Touch(false); } // SprEngine.Compile might have modified the database Program.MainForm.UpdateUI(false, null, false, null, false, null, false); return(true); }
private void LoadSecurityOptions() { AceWorkspaceLocking aceWL = Program.Config.Security.WorkspaceLocking; uint uLockTime = aceWL.LockAfterTime; bool bLockTime = (uLockTime > 0); m_numLockAfterTime.Value = (bLockTime ? uLockTime : 300); m_cbLockAfterTime.Checked = bLockTime; if (AppConfigEx.IsOptionEnforced(aceWL, "LockAfterTime")) { m_cbLockAfterTime.Enabled = false; } uLockTime = aceWL.LockAfterGlobalTime; bLockTime = (uLockTime > 0); m_numLockAfterGlobalTime.Value = (bLockTime ? uLockTime : 240); m_cbLockAfterGlobalTime.Checked = bLockTime; if (AppConfigEx.IsOptionEnforced(aceWL, "LockAfterGlobalTime")) { m_cbLockAfterGlobalTime.Enabled = false; } int nDefaultExpireDays = Program.Config.Defaults.NewEntryExpiresInDays; if (nDefaultExpireDays < 0) { m_cbDefaultExpireDays.Checked = false; } else { m_cbDefaultExpireDays.Checked = true; try { m_numDefaultExpireDays.Value = nDefaultExpireDays; } catch (Exception) { Debug.Assert(false); } } if (AppConfigEx.IsOptionEnforced(Program.Config.Defaults, "NewEntryExpiresInDays")) { m_cbDefaultExpireDays.Enabled = false; } int nClipClear = Program.Config.Security.ClipboardClearAfterSeconds; if (nClipClear >= 0) { m_cbClipClearTime.Checked = true; m_numClipClearTime.Value = nClipClear; } else { m_cbClipClearTime.Checked = false; } if (AppConfigEx.IsOptionEnforced(Program.Config.Security, "ClipboardClearAfterSeconds")) { m_cbClipClearTime.Enabled = false; } m_lvSecurityOptions.Columns.Add(string.Empty); // Resize below ListViewGroup lvg = new ListViewGroup(KPRes.Options); m_lvSecurityOptions.Groups.Add(lvg); Debug.Assert(lvg.ListView == m_lvSecurityOptions); m_cdxSecurityOptions = new CheckedLVItemDXList(m_lvSecurityOptions, true); bool? obNoSEv = null; // Allow read-only by enforced config string strSEvSuffix = string.Empty; if (MonoWorkarounds.IsRequired(1378)) { obNoSEv = true; strSEvSuffix = " (" + KPRes.UnsupportedByMono + ")"; } m_cdxSecurityOptions.CreateItem(aceWL, "LockOnWindowMinimize", lvg, KPRes.LockOnMinimizeTaskbar); m_cdxSecurityOptions.CreateItem(aceWL, "LockOnWindowMinimizeToTray", lvg, KPRes.LockOnMinimizeTray); m_cdxSecurityOptions.CreateItem(aceWL, "LockOnSessionSwitch", lvg, KPRes.LockOnSessionSwitch + strSEvSuffix, obNoSEv); m_cdxSecurityOptions.CreateItem(aceWL, "LockOnSuspend", lvg, KPRes.LockOnSuspend + strSEvSuffix, obNoSEv); m_cdxSecurityOptions.CreateItem(aceWL, "LockOnRemoteControlChange", lvg, KPRes.LockOnRemoteControlChange + strSEvSuffix, obNoSEv); m_cdxSecurityOptions.CreateItem(aceWL, "ExitInsteadOfLockingAfterTime", lvg, KPRes.ExitInsteadOfLockingAfterTime); m_cdxSecurityOptions.CreateItem(aceWL, "AlwaysExitInsteadOfLocking", lvg, KPRes.ExitInsteadOfLockingAlways); m_cdxSecurityOptions.CreateItem(Program.Config.Security, "ClipboardClearOnExit", lvg, KPRes.ClipboardClearOnExit); m_cdxSecurityOptions.CreateItem(Program.Config.Security, "UseClipboardViewerIgnoreFormat", lvg, KPRes.ClipboardViewerIgnoreFormat + " " + KPRes.NotRecommended); if (NativeLib.IsLibraryInstalled()) { m_cdxSecurityOptions.CreateItem(Program.Config.Native, "NativeKeyTransformations", lvg, KPRes.NativeLibUse); } bool?obNoWin = null; // Allow read-only by enforced config if (NativeLib.IsUnix()) { obNoWin = true; } m_cdxSecurityOptions.CreateItem(Program.Config.Security, "MasterKeyOnSecureDesktop", lvg, KPRes.MasterKeyOnSecureDesktop, obNoWin); m_cdxSecurityOptions.CreateItem(Program.Config.Security, "ClearKeyCommandLineParams", lvg, KPRes.ClearKeyCmdLineParams); m_cdxSecurityOptions.CreateItem(Program.Config.Security.MasterPassword, "RememberWhileOpen", lvg, KPRes.MasterPasswordRmbWhileOpen); m_cdxSecurityOptions.UpdateData(false); UIUtil.ResizeColumns(m_lvSecurityOptions, true); }
private static void ExportEntry(PwEntry pe, string strDir, PwExportInfo pxi) { PwDatabase pd = ((pxi != null) ? pxi.ContextDatabase : null); SprContext ctx = new SprContext(pe, pd, SprCompileFlags.NonActive, false, false); KeyValuePair <string, string>?okvpCmd = null; string strUrl = SprEngine.Compile(pe.Strings.ReadSafe(PwDefs.UrlField), ctx); if (WinUtil.IsCommandLineUrl(strUrl)) { strUrl = WinUtil.GetCommandLineFromUrl(strUrl); if (!NativeLib.IsUnix()) // LNKs only supported on Windows { string strApp, strArgs; StrUtil.SplitCommandLine(strUrl, out strApp, out strArgs); if (!string.IsNullOrEmpty(strApp)) { okvpCmd = new KeyValuePair <string, string>(strApp, strArgs); } } } if (string.IsNullOrEmpty(strUrl)) { return; } bool bLnk = okvpCmd.HasValue; string strTitleCmp = SprEngine.Compile(pe.Strings.ReadSafe(PwDefs.TitleField), ctx); if (string.IsNullOrEmpty(strTitleCmp)) { strTitleCmp = KPRes.Entry; } string strTitle = Program.Config.Defaults.WinFavsFileNamePrefix + strTitleCmp; string strSuffix = Program.Config.Defaults.WinFavsFileNameSuffix + (bLnk ? ".lnk" : ".url"); strSuffix = UrlUtil.FilterFileName(strSuffix); string strFileBase = (UrlUtil.EnsureTerminatingSeparator(strDir, false) + UrlUtil.FilterFileName(strTitle)); string strFile = strFileBase + strSuffix; int iFind = 2; while (File.Exists(strFile)) { strFile = strFileBase + " (" + iFind.ToString() + ")" + strSuffix; ++iFind; } if (!Directory.Exists(strDir)) { try { Directory.CreateDirectory(strDir); } catch (Exception exDir) { throw new Exception(strDir + MessageService.NewParagraph + exDir.Message); } WaitForDirCommit(strDir, true); } try { if (bLnk) { int ccMaxDesc = NativeMethods.INFOTIPSIZE - 1 - LnkDescSuffix.Length; string strDesc = StrUtil.CompactString3Dots(strUrl, ccMaxDesc) + LnkDescSuffix; ShellLinkEx sl = new ShellLinkEx(okvpCmd.Value.Key, okvpCmd.Value.Value, strDesc); sl.Save(strFile); } else { StringBuilder sb = new StringBuilder(); sb.AppendLine(@"[InternetShortcut]"); sb.AppendLine(@"URL=" + strUrl); // No additional line break sb.AppendLine(@"[" + PwDefs.ShortProductName + @"]"); sb.AppendLine(IniTypeKey + @"=" + IniTypeValue); // Terminating line break is important File.WriteAllText(strFile, sb.ToString(), Encoding.Default); } } catch (Exception exWrite) { throw new Exception(strFile + MessageService.NewParagraph + exWrite.Message); } }
public static void SendKeysWait(string strKeys, bool bObfuscate) { if (strKeys == null) { Debug.Assert(false); return; } List <SiEvent> l = Parse(strKeys); if (l.Count == 0) { return; } if (bObfuscate) { SiObf.Obfuscate(l); } FixEventSeq(l); ISiEngine si = null; if (SendInputEx.CreateEngine != null) { SiEventArgs ea = new SiEventArgs(); SendInputEx.CreateEngine(null, ea); si = ea.Engine; } if (si == null) { if (NativeLib.IsUnix()) { si = new SiEngineUnix(); } else { si = new SiEngineWin(); } } bool bInter = Program.Config.Integration.AutoTypeAllowInterleaved; if (!bInter) { if (!g_csSending.TryEnter()) { return; } } Interlocked.Increment(ref g_cCurSending); try { si.Init(); Send(si, l); } finally { try { si.Release(); } catch (Exception) { Debug.Assert(false); } Interlocked.Decrement(ref g_cCurSending); if (!bInter) { g_csSending.Exit(); } } }