private void ThreadMain(object[] parameters) { IDisposable splashScreen = null; if (parameters.Length > 0) { splashScreen = parameters[parameters.Length - 1] as IDisposable; } ProcessKeepalive pk = null; try { try { pk = ProcessKeepalive.Open(); } finally { object signalIncremented = parameters[0]; lock (signalIncremented) Monitor.Pulse(parameters[0]); } // housekeeping initialization Application.OleRequired(); UnexpectedErrorDelegate.RegisterWindowsHandler(); // Create and run the form SatelliteApplicationForm applicationForm = (SatelliteApplicationForm)Activator.CreateInstance(_formType, _parameters); Application.Run(applicationForm); } catch (Exception ex) { UnexpectedErrorMessage.Show(ex); } finally { if (pk != null) { pk.Dispose(); } if (splashScreen != null) { Debug.Assert(splashScreen is FormSplashScreen); splashScreen.Dispose(); } } }
protected override void OnClick(EventArgs e) { base.OnClick(e); try { BlogEditingTemplateDetector detector = new BlogEditingTemplateDetector(this); detector.SetContext("http://localhost/test/editingTemplate.htm", @"C:\Program Files\Apache Group\Apache\htdocs\test\blogtemplates"); detector.DetectTemplate(SilentProgressHost.Instance); Trace.WriteLine(detector.BlogTemplateFile); } catch (Exception ex) { UnexpectedErrorMessage.Show(ex); } }
// This method is called on a worker thread (via asynchronous // delegate invocation). This is where we call the operation (as // defined in the deriving class's DoWork method). private void InternalStart() { // Reset our state - we might be run more than once. cancelledFlag = false; completeFlag = false; cancelAcknowledgedFlag = false; failedFlag = false; // isRunning is set during Start to avoid a race condition try { DoWork(); } catch (Exception e) { // Raise the Failed event. We're in a catch handler, so we // had better try not to throw another exception. try { FailOperation(e); } catch { } } try { lock (this) { // If the operation wasn't cancelled (or if the UI thread // tried to cancel it, but the method ran to completion // anyway before noticing the cancellation) and it // didn't fail with an exception, then we complete the // operation - if the UI thread was blocked waiting for // cancellation to complete it will be unblocked, and // the Completion event will be raised. if (!cancelAcknowledgedFlag && !failedFlag) { CompleteOperation(); } } } catch (Exception e) { UnexpectedErrorMessage.Show(e); } }
public static void Main(string[] args) { try { // initialize application environment ApplicationEnvironment.Initialize(); //RsdServiceDescription rsdService = RsdServiceDetector.DetectFromRsdUrl("http://localhost/test/foo.rsd", 10000); //Trace.WriteLine(rsdService.EditingTemplateLink); Application.Run(new TestForm()); // launch blogging form //WeblogConfigurationWizardController.Add(Win32WindowImpl.DesktopWin32Window); //WeblogConfigurationWizardController.Edit(Win32WindowImpl.DesktopWin32Window, BlogSettings.DefaultBlogId); } catch (Exception ex) { UnexpectedErrorMessage.Show(ex); } }
protected override void OnFormClosing(FormClosingEventArgs e) { try { // Suppress all events from the ApplicationManager's CommandManager. The .NET event // model is just not up to how we use it, and we will receive events on disposed // controls which .NET will use to reload them. if (_postEditorMainControl != null) { _postEditorMainControl.CommandManager.SuppressEvents = true; } } catch (Exception ex) { // An uncaught exception here stops the user from ever being able to // close the window (other than TaskMan), so we'll Watson but continue. UnexpectedErrorMessage.Show(this, ex); } base.OnFormClosing(e); }
protected override void OnLoad(EventArgs e) { try { base.OnLoad(e); SuspendLayout(); // initialize the workspace OnInitializeWorkspace(); ribbonLoaded = true; // restore window state RestoreWindowState(); ResumeLayout(); } catch (Exception ex) { UnexpectedErrorMessage.Show(Win32WindowImpl.DesktopWin32Window, ex); Close(); } }
private void buttonFindNext_Click(object sender, System.EventArgs e) { try { string findText = textBoxFindWhat.Text.Trim(); int nextOccurance = -1; if (radioButtonDown.Checked) { nextOccurance = _targetTextBox.Text.IndexOf(findText, _targetTextBox.SelectionStart + _targetTextBox.SelectionLength); } else { int start = _targetTextBox.SelectionStart; if (_targetTextBox.SelectionLength == 1 && start > 0) { start = start - 1; } nextOccurance = _targetTextBox.Text.LastIndexOf(findText, start); } if (nextOccurance != -1) { _targetTextBox.Select(nextOccurance, findText.Length); _targetTextBox.ScrollToCaret(); } else { DisplayMessage.Show(MessageId.FinishedSearchingDocument, this); } } catch (Exception ex) { UnexpectedErrorMessage.Show(this, ex); } }
/// <summary> /// Launches a window as part of the starting of a process. /// </summary> private static void LaunchFirstInstance(IDisposable splashScreen, string[] args) { try { PostEditorFile.Initialize(); MaybeMigrateSettings(); // Make sure editor options are available before we launch the first instance. GlobalEditorOptions.Init(new OpenLiveWriterContentTarget(), new OpenLiveWriterSettingsProvider()); // register file associations // Removing this call, as it causes exceptions in Vista // RegisterFileAssociations() ; Trace.WriteLine(String.Format(CultureInfo.InvariantCulture, "Starting {0} {1}", ApplicationEnvironment.ProductNameQualified, ApplicationEnvironment.ProductVersion)); Trace.WriteLine(String.Format(CultureInfo.InvariantCulture, ".NET version: {0}", Environment.Version)); // force initialization which may fail with error dialogs // and/or cause the whole application to not load if (PostEditorLifetimeManager.Initialize()) { initComplete = true; // launch blogging form ApplicationLauncher.LaunchBloggingForm(args, splashScreen, true); } ManualKeepalive.Wait(true); } catch (DirectoryException ex) { if (ex.MessageId != null) { DisplayMessage.Show(ex.MessageId.Value); } else if (ex.Path != null) { DisplayMessage.Show(MessageId.DirectoryFail, ex.Path); } else { UnexpectedErrorMessage.Show(ex); } } catch (Exception ex) { UnexpectedErrorMessage.Show(ex); } finally { try { // shut down PostEditorLifetimeManager.Uninitialize(); TempFileManager.Instance.Dispose(); // Delete legacy post supporting files that might have // been orphaned by a previous version of Writer. We // now keep these in the temp directory like everything // else string legacyPostSupportingFiles = Path.Combine(ApplicationEnvironment.ApplicationDataDirectory, "PostSupportingFiles"); if (Directory.Exists(legacyPostSupportingFiles)) { Directory.Delete(legacyPostSupportingFiles, true); } } catch (Exception ex2) { Trace.Fail(ex2.ToString()); } } }
/// <summary> /// The hook procedure for window messages generated by the FileOpenDialog /// </summary> /// <param name="hWnd">the handle of the window at which this message is targeted</param> /// <param name="msg">the message identifier</param> /// <param name="wParam">message-specific parameter data</param> /// <param name="lParam">mess-specific parameter data</param> /// <returns></returns> public IntPtr MyHookProc(IntPtr hWnd, UInt32 msg, Int32 wParam, Int32 lParam) { try { if (hWnd == IntPtr.Zero) { return(IntPtr.Zero); } switch (msg) { // We're not interested in every possible message; just return a NULL for those we don't care about default: { return(IntPtr.Zero); } // WM_INITDIALOG - at this point the OpenFileDialog exists, so we pull the user-supplied control // into the FileOpenDialog now, using the SetParent API. case WM.INITDIALOG: { _hWndParent = User32.GetParent(hWnd); //setting a bool for whether the OS is RTL (not the installed language of WLW) IsRTL = (User32.GetWindowLong(_hWndParent, User32.GWL_EXSTYLE) & User32.WS_EX_LAYOUTRTL) > 0; //account for large title bar, borders for adjusting control locations TITLEBARINFO titleBarInfo = new TITLEBARINFO(); titleBarInfo.cbSize = (uint)Marshal.SizeOf(titleBarInfo); if (!User32.GetTitleBarInfo(_hWndParent, ref titleBarInfo)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } WINDOWINFO info = new WINDOWINFO(); info.cbSize = (uint)Marshal.SizeOf(info); if (!User32.GetWindowInfo(_hWndParent, ref info)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } _extraWindowHeight = (titleBarInfo.rcTitleBar.bottom - titleBarInfo.rcTitleBar.top) + 2 * (int)info.cyWindowBorders; _extraWindowWidth = 2 * (int)info.cxWindowBorders; Rectangle rcClient = new Rectangle(0, 0, 0, 0); // Get client rectangle of dialog RECT rcTemp = new RECT(); User32.GetWindowRect(_hWndParent, ref rcTemp); rcClient.X = rcTemp.left; rcClient.Y = rcTemp.top; rcClient.Width = rcTemp.Width; rcClient.Height = rcTemp.Height + TABS_HEIGHT + BUTTONS_HEIGHT; //make the dialog box bigger User32.MoveWindow(_hWndParent, rcClient.Left, rcClient.Top, rcClient.Width, rcClient.Height, true); //move all the controls down AdjustControlLocations(); //top tab control mainTabControl = new LightweightControlContainerControl(); User32.SetParent(mainTabControl.Handle, _hWndParent); mainTabControl.Location = new Point(0, 0); mainTabControl.Anchor = AnchorStyles.Left | AnchorStyles.Right; mainTabControl.Size = new Size(rcClient.Width, TABS_HEIGHT); tabs = new TabLightweightControl(); tabs.ColorizeBorder = false; tabs.VirtualBounds = new Rectangle(0, 0, rcClient.Width, TABS_HEIGHT); tabs.LightweightControlContainerControl = mainTabControl; tabs.DrawSideAndBottomTabPageBorders = false; InsertImageTabControl tabFromFile = new InsertImageTabControl(); tabFromFile.TabText = Res.Get(StringId.InsertImageInsertFromFile); tabFromFile.TabBitmap = ResourceHelper.LoadAssemblyResourceBitmap("ImageInsertion.Images.TabInsertFromFile.png"); tabFromFile.BackColor = SystemColors.Control; User32.SetParent(tabFromFile.Handle, _hWndParent); tabs.SetTab(0, tabFromFile); mainTabControl.BackColor = tabFromFile.ApplicationStyle.InactiveTabTopColor; //now, add tabs for the other controls int i = 1; foreach (InsertImageSource imageSource in imageSources) { InsertImageTabControl tab = new InsertImageTabControl(); tab.TabText = imageSource.TabName; tab.TabBitmap = imageSource.TabBitmap; tab.BackColor = SystemColors.Control; tabs.SetTab(i++, tab); } tabs.SelectedTabNumberChanged += new EventHandler(tabs_SelectedTabNumberChanged); //set the keyboard hook for tab switching tabKeyboardHook = new TabbingHookProc(tabs); tabKeyboardHook.Install(_hWndParent); //add other image source panels _panelImage = new Panel(); _panelImage.Location = new Point(0, mainTabControl.Size.Height); _panelImage.BorderStyle = BorderStyle.None; _panelImage.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top | AnchorStyles.Bottom; _panelImage.Size = new Size(rcClient.Width, rcClient.Height - TABS_HEIGHT - BUTTONS_HEIGHT - _extraWindowHeight); _panelImage.Visible = false; User32.SetParent(_panelImage.Handle, _hWndParent); //initalize the other sources foreach (InsertImageSource source in imageSources) { source.Init(_panelImage.Width, _panelImage.Height); Control c = source.ImageSelectionControls; DisplayHelper.Scale(c); foreach (Control childControl in c.Controls) { DisplayHelper.Scale(childControl); } } DisplayHelper.Scale(_panelImage); //special cancel button _buttonPanel = new Panel(); _buttonPanel.Location = new Point(rcClient.Width - (int)(0.5 * _extraWindowWidth) - _buttonPanel.Width, _panelImage.Bounds.Bottom); _buttonPanel.Size = new Size(75, 23); _buttonPanel.BorderStyle = BorderStyle.None; _cancelButton = new Button(); _cancelButton.TextAlign = ContentAlignment.MiddleCenter; if (BidiHelper.IsRightToLeft) { _cancelButton.RightToLeft = RightToLeft.Yes; } _cancelButton.Text = Res.Get(StringId.CancelButton); _cancelButton.FlatStyle = FlatStyle.System; _cancelButton.Location = new Point(0, 0); _cancelButton.Size = new Size(75, 23); _cancelButton.Click += new EventHandler(_cancelButton_Click); _buttonPanel.Controls.Add(_cancelButton); User32.SetParent(_buttonPanel.Handle, _hWndParent); int origWidth = _cancelButton.Width; string tmp = _cancelButton.Text; _cancelButton.Text = Res.Get(StringId.InsertImageButton); int newWidth = Math.Max(origWidth, DisplayHelper.MeasureButton(_cancelButton)); _cancelButton.Text = tmp; newWidth = Math.Max(newWidth, DisplayHelper.MeasureButton(_cancelButton)); _buttonPanel.Width = _cancelButton.Width = newWidth; int deltaX = newWidth - origWidth; _buttonPanel.Left -= deltaX; //fixing up button text and tab order IntPtr hWndOpenButton = User32.GetDlgItem(_hWndParent, _OPEN_BUTTON_ID); User32.SetWindowText(hWndOpenButton, Res.Get(StringId.InsertImageButton)); mainTabControl.InitFocusManager(); mainTabControl.AddFocusableControls(tabs.GetAccessibleControls()); foreach (InsertImageSource tabPage in imageSources) { mainTabControl.AddFocusableControl(tabPage.ImageSelectionControls); } state = STATE.FILE; return(IntPtr.Zero); } case WM.SIZE: { ManipulatePanels(); return(IntPtr.Zero); } // WM_NOTIFY - we're only interested in the CDN_SELCHANGE notification message: // we grab the currently-selected filename and copy it into the buffer case WM.NOTIFY: { IntPtr ipNotify = new IntPtr(lParam); OfNotify ofNot = (OfNotify)Marshal.PtrToStructure(ipNotify, typeof(OfNotify)); Int16 code = (short)ofNot.hdr.code; if (code == CommonDlgNotification.SelChange) { UpdateChosenImage(false); //CheckOptions(false); } else if (code == CommonDlgNotification.InitDone) { listener = new CommandListener(_hWndParent, this, (int)User32.GetDlgCtrlID(_cancelButton.Handle)); } else if (code == CommonDlgNotification.FileOk) { // update the image path (need to do this if the user selected // a file by simpliy typing in the filepath text box) UpdateChosenImage(true); // ok to insert _insertFile = true; } else if ((code == CommonDlgNotification.FolderChange) && (state == STATE.WEB)) { // If the user hits the OK button while there is no valid selection // within the File panel, the file dialog sends a CommonDlgNotification.FolderChange // We use this combined with other relevant state to trigger the closing // of the Image dialog HitOpen(); } return(IntPtr.Zero); } } } catch (Exception ex) { UnexpectedErrorMessage.Show(ex); return(new IntPtr(1)); } finally { GC.KeepAlive(this); } }
/// <summary> /// Notify the user that an unexpected exception has occurred. In addition to /// displaying an error message to the user this method also automatically logs /// the unexpected exception in the Open Live Writer log file. /// </summary> /// <param name="ex">Unexpected exception.</param> public static void DisplayUnexpectedException(Exception ex) { LogException(ex); UnexpectedErrorMessage.Show(ex); }