public static void ShowError(this Exception e, IntPtr windowHandle) { IWin32Window parentWin32 = null; if (windowHandle != IntPtr.Zero) { try { var nw = new NativeWindow(); nw.AssignHandle(windowHandle); parentWin32 = nw; } catch { parentWin32 = null; } } if (parentWin32 != null) { MessageBox.Show(parentWin32, FormatError(e), "innoGlue internal error", MessageBoxButtons.OK, MessageBoxIcon.Hand); } else { MessageBox.Show(FormatError(e), "innoGlue internal error", MessageBoxButtons.OK, MessageBoxIcon.Hand); } }
public IWindowInfo GetInfoFrom(NativeWindow window) { if (window == null) throw new ArgumentException("NativeWindow cannot be null."); return new WindowInfo(window); }
public void Execute(object sender, EventArgs e) { var dte = (EnvDTE.DTE)_visualStudioPackageProvider.Package.DTE; //GetService(typeof(EnvDTE.DTE)); var uiShell = _visualStudioPackageProvider.Package.VsUIShell; var parentHwnd = IntPtr.Zero; uiShell.GetDialogOwnerHwnd(out parentHwnd); var parentShim = new NativeWindow(); parentShim.AssignHandle(parentHwnd); var dialog = new AttachDialog(); var result = dialog.ShowDialog(parentShim); if (result == DialogResult.OK) { HashSet<Process> processes = new HashSet<Process>(); foreach (int pid in dialog.SelectedItems) { Process p = Process.GetProcessById(pid); if (!p.IsBeingDebugged()) processes.Add(p); if (dialog.AutoAttachToCurrentChildren) { foreach (Process child in p.GetChildren()) { if (!child.IsBeingDebugged()) processes.Add(child); } } } List<Process> processList = new List<Process>(processes); ChildDebuggingMode mode = (dialog.AutoAttachToFutureChildren) ? ChildDebuggingMode.AlwaysAttach : ChildDebuggingMode.UseDefault; DebugAttach.AttachToProcess(processList.ToArray(), mode); } }
private void btnBrowseClear_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) { var nativeWindow = new WinForms.NativeWindow(); nativeWindow.AssignHandle(new WindowInteropHelper(this).Handle); var oldSaveLoc = Properties.Settings.Default.exportPath; var dlg = new WinForms.FolderBrowserDialog(); if (!string.IsNullOrEmpty(oldSaveLoc)) { dlg.SelectedPath = oldSaveLoc; } else { dlg.SelectedPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); } var result = dlg.ShowDialog(nativeWindow); if (result == WinForms.DialogResult.OK) { string newSavePath = dlg.SelectedPath; if (!string.IsNullOrEmpty(newSavePath)) { txtExportPath.Text = newSavePath; Properties.Settings.Default.exportPath = newSavePath; Properties.Settings.Default.Save(); } } }
private void OnButtonOne_Click(object sender, EventArgs e) { MainForm form = new MainForm(); System.Windows.Forms.NativeWindow nw = System.Windows.Forms.NativeWindow.FromHandle(this.Handle); form.Show(nw); }
void InitialShow() { NativeWindow owner = new NativeWindow(); owner.AssignHandle(((HwndSource)HwndSource.FromVisual(_owner)).Handle); _form.Show(owner); owner.ReleaseHandle(); }
public SuspendDrawing(Control control) { this.control = control; var msgSuspendUpdate = Message.Create(this.control.Handle, WM_SETREDRAW, IntPtr.Zero, IntPtr.Zero); window = NativeWindow.FromHandle(this.control.Handle); window.DefWndProc(ref msgSuspendUpdate); }
public WindowInfo(NativeWindow window) { if (window == null) throw new ArgumentException("NativeWindow cannot be null."); this.Handle = window.Handle; this.Parent = null; }
public WindowInfo(NativeWindow window) { if (window == null) throw new ArgumentException("NativeWindow cannot be null."); this.CopyInfoFromXPlatUI(); this.Handle = window.Handle; this.Parent = null; this.TopLevelWindow = IntPtr.Zero; }
public LynnTextbox() { this.ImeMode = ImeMode.On; if (UIManager.Enabled) { this.SetStyle(ControlStyles.AllPaintingInWmPaint, true); native2 = new NativeBorder(this, 0xf /* WM_PAINT */, true, false); native = new NativeBorder(this, 0x85 /* WM_NCPAINT */); } }
public PlayerWindow() { InitializeComponent(); PlaylistWindow = new PlaylistWindow(); NativeWindow natRef = new NativeWindow(); natRef.AssignHandle(this.Handle); PlaylistWindow.Show(natRef); PlaylistWindow.Visible = false; Rectangle ScreenBounds = Screen.FromHandle(this.Handle).Bounds; Program.snappingManager.bounds[IntPtr.Zero] = ScreenBounds; trackBar1_ValueChanged(trackBar1, null); }
public LynnCombobox() { native = new NativeBorder(this, 0xf /* WM_PAINT */, true, false); native2 = new NativeBorder(this, 0x85 /* WM_NCPAINT */, true, false); base.DrawMode = DrawMode.OwnerDrawFixed; this.IntegralHeight = false; stringFormat = new StringFormat(StringFormatFlags.NoClip | StringFormatFlags.NoWrap); stringFormat.LineAlignment = StringAlignment.Center; stringFormat.Trimming = StringTrimming.EllipsisCharacter; stringFormat.HotkeyPrefix = System.Drawing.Text.HotkeyPrefix.None; OnFontChanged(EventArgs.Empty); }
public LynnListbox() : base() { native2 = new UI.NativeBorder(this, 0xf /* WM_NCPAINT */, false, false); native = new UI.NativeBorder(this, 0x85 /* WM_NCPAINT */, false, false); base.DrawMode = DrawMode.OwnerDrawFixed; this.IntegralHeight = false; stringFormat = new StringFormat(StringFormatFlags.NoClip | StringFormatFlags.NoWrap); stringFormat.LineAlignment = StringAlignment.Center; stringFormat.Trimming = StringTrimming.EllipsisCharacter; stringFormat.HotkeyPrefix = System.Drawing.Text.HotkeyPrefix.None; OnFontChanged(EventArgs.Empty); }
private ShowDesktop() { // create a reference window to detect show desktop referenceWindow = new NativeWindow(); CreateParams cp = new CreateParams(); cp.ExStyle = GadgetWindow.WS_EX_TOOLWINDOW; cp.Caption = referenceWindowCaption; referenceWindow.CreateHandle(cp); NativeMethods.SetWindowPos(referenceWindow.Handle, GadgetWindow.HWND_BOTTOM, 0, 0, 0, 0, GadgetWindow.SWP_NOMOVE | GadgetWindow.SWP_NOSIZE | GadgetWindow.SWP_NOACTIVATE | GadgetWindow.SWP_NOSENDCHANGING); // start a repeated timer to detect "Show Desktop" events timer = new System.Threading.Timer(OnTimer, null, System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite); }
/// <summary> /// Returns a rectangle representing the location of the specified NotifyIcon. (Windows 7+.) /// </summary> /// <param name="notifyicon">The NotifyIcon whose location should be returned.</param> /// <returns>The location of the specified NotifyIcon. Null if the location could not be found.</returns> public static Rect?GetNotifyIconRectWindows7(NotifyIcon notifyicon) { if (Compatibility.CurrentWindowsVersion != Compatibility.WindowsVersion.Windows7Plus) { throw new PlatformNotSupportedException("This method can only be used under Windows 7 or later. Please use GetNotifyIconRectangleLegacy() if you use an earlier operating system."); } // get notify icon id FieldInfo idFieldInfo = notifyicon.GetType().GetField("id", BindingFlags.NonPublic | BindingFlags.Instance); int iconid = (int)idFieldInfo.GetValue(notifyicon); // get notify icon hwnd IntPtr iconhandle; try { FieldInfo windowFieldInfo = notifyicon.GetType().GetField("window", BindingFlags.NonPublic | BindingFlags.Instance); System.Windows.Forms.NativeWindow nativeWindow = (System.Windows.Forms.NativeWindow)windowFieldInfo.GetValue(notifyicon); iconhandle = nativeWindow.Handle; if (iconhandle == null || iconhandle == IntPtr.Zero) { return(null); } } catch { return(null); } NativeMethods.RECT rect = new NativeMethods.RECT(); NativeMethods.NOTIFYICONIDENTIFIER nid = new NativeMethods.NOTIFYICONIDENTIFIER() { hWnd = iconhandle, uID = (uint)iconid }; nid.cbSize = (uint)Marshal.SizeOf(nid); int result = NativeMethods.Shell_NotifyIconGetRect(ref nid, out rect); // 0 means success, 1 means the notify icon is in the fly-out - either is fine if (result != 0 && result != 1) { return(null); } // convert to System.Rect and return return(rect); }
// will ensure that the toolTip window was created public void CreateToolTipHandle() { if (tipWindow == null || tipWindow.Handle == IntPtr.Zero) { NativeMethods.INITCOMMONCONTROLSEX icc = new NativeMethods.INITCOMMONCONTROLSEX(); icc.dwICC = NativeMethods.ICC_TAB_CLASSES; icc.dwSize = Marshal.SizeOf(icc); SafeNativeMethods.InitCommonControlsEx(icc); CreateParams cparams = new CreateParams(); cparams.Parent = dataGrid.Handle; cparams.ClassName = NativeMethods.TOOLTIPS_CLASS; cparams.Style = NativeMethods.TTS_ALWAYSTIP; tipWindow = new NativeWindow(); tipWindow.CreateHandle(cparams); UnsafeNativeMethods.SendMessage(new HandleRef(tipWindow, tipWindow.Handle), NativeMethods.TTM_SETMAXTIPWIDTH, 0, SystemInformation.MaxWindowTrackSize.Width); SafeNativeMethods.SetWindowPos(new HandleRef(tipWindow, tipWindow.Handle), NativeMethods.HWND_NOTOPMOST, 0, 0, 0, 0, NativeMethods.SWP_NOSIZE | NativeMethods.SWP_NOMOVE | NativeMethods.SWP_NOACTIVATE); UnsafeNativeMethods.SendMessage(new HandleRef(tipWindow, tipWindow.Handle), NativeMethods.TTM_SETDELAYTIME, NativeMethods.TTDT_INITIAL, 0); } }
public void CreateToolTipHandle() { if ((this.tipWindow == null) || (this.tipWindow.Handle == IntPtr.Zero)) { System.Windows.Forms.NativeMethods.INITCOMMONCONTROLSEX initcommoncontrolsex; initcommoncontrolsex = new System.Windows.Forms.NativeMethods.INITCOMMONCONTROLSEX { dwICC = 8, dwSize = Marshal.SizeOf(initcommoncontrolsex) }; System.Windows.Forms.SafeNativeMethods.InitCommonControlsEx(initcommoncontrolsex); CreateParams cp = new CreateParams { Parent = this.dataGrid.Handle, ClassName = "tooltips_class32", Style = 1 }; this.tipWindow = new NativeWindow(); this.tipWindow.CreateHandle(cp); System.Windows.Forms.UnsafeNativeMethods.SendMessage(new HandleRef(this.tipWindow, this.tipWindow.Handle), 0x418, 0, SystemInformation.MaxWindowTrackSize.Width); System.Windows.Forms.SafeNativeMethods.SetWindowPos(new HandleRef(this.tipWindow, this.tipWindow.Handle), System.Windows.Forms.NativeMethods.HWND_NOTOPMOST, 0, 0, 0, 0, 0x13); System.Windows.Forms.UnsafeNativeMethods.SendMessage(new HandleRef(this.tipWindow, this.tipWindow.Handle), 0x403, 3, 0); } }
public static Rect?GetNotifyIconRectangle(NotifyIcon notifyicon) { // get notify icon id FieldInfo idFieldInfo = notifyicon.GetType().GetField("id", BindingFlags.NonPublic | BindingFlags.Instance); int iconid = (int)idFieldInfo.GetValue(notifyicon); // get notify icon hwnd FieldInfo windowFieldInfo = notifyicon.GetType().GetField("window", BindingFlags.NonPublic | BindingFlags.Instance); System.Windows.Forms.NativeWindow nativeWindow = (System.Windows.Forms.NativeWindow)windowFieldInfo.GetValue(notifyicon); IntPtr iconhandle = nativeWindow.Handle; if (iconhandle == IntPtr.Zero) { return(null); } RECT rect = new RECT(); NOTIFYICONIDENTIFIER nid = new NOTIFYICONIDENTIFIER() { hWnd = iconhandle, uID = (uint)iconid }; nid.cbSize = (uint)Marshal.SizeOf(nid); int result = Shell_NotifyIconGetRect(ref nid, out rect); // 0 means success, 1 means the notify icon is in the fly-out - either is fine if (result != 0 && result != 1) { return(null); } // convert to System.Rect and return return(rect); }
/// <devdoc> /// WM_NCDESTROY handler /// </devdoc> /// <internalonly/> private void WmNCDestroy(ref Message m) { MainMenu mainMenu = Menu; MainMenu dummyMenu = (MainMenu)Properties.GetObject(PropDummyMenu); MainMenu curMenu = (MainMenu)Properties.GetObject(PropCurMenu); MainMenu mergedMenu = (MainMenu)Properties.GetObject(PropMergedMenu); if (mainMenu != null) { mainMenu.ClearHandles(); } if (curMenu != null) { curMenu.ClearHandles(); } if (mergedMenu != null) { mergedMenu.ClearHandles(); } if (dummyMenu != null) { dummyMenu.ClearHandles(); } base.WndProc(ref m); // Destroy the owner window, if we created one. We // cannot do this in OnHandleDestroyed, because at // that point our handle is not actually destroyed so // destroying our parent actually causes a recursive // WM_DESTROY. if (ownerWindow != null) { ownerWindow.DestroyHandle(); ownerWindow = null; } if (Modal && dialogResult == DialogResult.None) { DialogResult = DialogResult.Cancel; } }
private static void AddWindowToTable(IntPtr handle, NativeWindow window) { lock (internalSyncObject) { uint num; uint num2; if (handleCount >= hashLoadSize) { ExpandTable(); } anyHandleCreated = true; anyHandleCreatedInApp = true; uint num3 = InitHash(handle, hashBuckets.Length, out num, out num2); int num4 = 0; int index = -1; GCHandle handle2 = GCHandle.Alloc(window, GCHandleType.Weak); do { int num6 = (int) (num % hashBuckets.Length); if (((index == -1) && (hashBuckets[num6].handle == new IntPtr(-1))) && (hashBuckets[num6].hash_coll < 0)) { index = num6; } if ((hashBuckets[num6].handle == IntPtr.Zero) || ((hashBuckets[num6].handle == new IntPtr(-1)) && ((hashBuckets[num6].hash_coll & 0x80000000L) == 0L))) { if (index != -1) { num6 = index; } hashBuckets[num6].window = handle2; hashBuckets[num6].handle = handle; hashBuckets[num6].hash_coll |= (int) num3; handleCount++; goto Label_0269; } if (((hashBuckets[num6].hash_coll & 0x7fffffff) == num3) && (handle == hashBuckets[num6].handle)) { GCHandle handle3 = hashBuckets[num6].window; if (handle3.IsAllocated) { window.previousWindow = (NativeWindow) handle3.Target; window.previousWindow.nextWindow = window; handle3.Free(); } hashBuckets[num6].window = handle2; goto Label_0269; } if (index == -1) { hashBuckets[num6].hash_coll |= -2147483648; } num += num2; } while (++num4 < hashBuckets.Length); if (index != -1) { hashBuckets[index].window = handle2; hashBuckets[index].handle = handle; hashBuckets[index].hash_coll |= (int) num3; handleCount++; } Label_0269:; } }
// will destroy the tipWindow public void Destroy() { Debug.Assert(tipWindow != null, "how can one destroy a null window"); tipWindow.DestroyHandle(); tipWindow = null; }
internal DialogResult ShowDialogExt(FileDialog fdlg,IWin32Window owner) { DialogResult returnDialogResult = DialogResult.Cancel; if (this.IsDisposed) return returnDialogResult; if (owner == null || owner.Handle == IntPtr.Zero) { WindowWrapper wr = new WindowWrapper(System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle); owner = wr; } OriginalCtrlSize = this.Size; MSDialog = fdlg; _dlgWrapper = new WholeDialogWrapper(this); try { System.Reflection.PropertyInfo AutoUpgradeInfo = MSDialog.GetType().GetProperty("AutoUpgradeEnabled"); if (AutoUpgradeInfo != null) AutoUpgradeInfo.SetValue(MSDialog, false, null); returnDialogResult = _MSdialog.ShowDialog(owner); } // Sometimes if you open a animated .gif on the preview and the Form is closed, .Net class throw an exception // Lets ignore this exception and keep closing the form. catch (ObjectDisposedException) { } catch (Exception ex) { MessageBox.Show("unable to get the modal dialog handle", ex.Message); } return returnDialogResult; }
public IDoxSession CreateAuthenticatedSession(string defaultUserEmail) { var outlookWindow = new NativeWindow(); try { outlookWindow.AssignHandle(FindWindowEx(IntPtr.Zero, IntPtr.Zero, "rctrl_renwnd32", null)); _loginUi.NativeWindow = outlookWindow; _loginUi.LoginFieldEnabled = true; _loginUi.RegisterTabVisible = true; IAuthenticator authenticator = new Authenticator(_loginUi); authenticator.Api = new DoxApi(OptionApi.GetString("SendLinkServiceUrl")); string username = OptionApi.GetString("SendLinkCloudStorageLoginName"); username = string.IsNullOrEmpty(username) ? defaultUserEmail : username; string deviceToken = OptionApi.GetEncrypted("SendLinkDeviceToken", _entropy); bool cancelled; var session = authenticator.Authenticate(username, deviceToken, out cancelled); if (cancelled) { throw new AbortSendLinkException("User cancelled Sendlink", false); } return session; } finally { if (outlookWindow != null) { // TFS 6777: Outlook 2010 + Interwoven EMM: On cancel, Mail Inspector "Send" button inoperable, outlook remains in memory. outlookWindow.ReleaseHandle(); } } }
public ProbeNppPlugin() { try { _instance = this; _nppWindow = NppWindow; _settings = new Settings(this); try { _settings.Load(); } catch (Exception ex) { Errors.Show(_nppWindow, ex, "Exception when attempting to load ProbeNpp settings."); } ProbeEnvironment.Initialize(); ProbeEnvironment.AppChanged += new EventHandler(_env_AppChanged); TempManager.Init(Path.Combine(ConfigDir, "Temp")); LoadLexerConfig(); _autoCompletionManager = new AutoCompletion.AutoCompletionManager(); _smartIndentManager = new AutoCompletion.SmartIndentManager(); Ready += new NppEventHandler(Plugin_Ready); Shutdown += new NppEventHandler(Plugin_Shutdown); FileOpened += new FileEventHandler(Plugin_FileOpened); FileClosed += new FileEventHandler(Plugin_FileClosed); FileActivated += new FileEventHandler(Plugin_FileActivated); FileSaved += new FileEventHandler(ProbeNppPlugin_FileSaved); LanguageChanged += new LanguageTypeEventHandler(Plugin_LanguageChanged); SelectionChanged += new NppEventHandler(Plugin_SelectionChanged); Modification += new ModifiedEventHandler(Plugin_Modification); CharAdded += new CharAddedEventHandler(ProbeNppPlugin_CharAdded); _fileBackground.Execute += new EventHandler(FileBackground_Execute); _functionFileScanner = new AutoCompletion.FunctionFileScanner(); _fileScannerDefer.Execute += new EventHandler(FileScanner_Execute); _fileScannerDefer.Activity += new EventHandler(FileScanner_Activity); } catch (Exception ex) { Errors.Show(_nppWindow, ex, "The ProbeNpp plug-in thrown an error while initializing."); } }
/// <summary> /// Constructs a new instance of a CopyData channel. Called /// automatically by the CopyDataChannels collection. /// </summary> /// <param name="owner">The owning native window</param> /// <param name="channelName">The name of the channel to /// send messages on</param> internal CopyDataChannel(NativeWindow owner, string channelName) { this.owner = owner; this.channelName = channelName; addChannel(); }
internal override IntPtr SendMessage(IntPtr hwnd, Msg message, IntPtr wParam, IntPtr lParam) { return(NativeWindow.WndProc(hwnd, message, wParam, lParam)); }
/// <summary> /// Returns a rectangle representing the location of the specified NotifyIcon. (Windows Vista and earlier.) /// </summary> /// <param name="notifyicon">The NotifyIcon whose location should be returned.</param> /// <returns>The location of the specified NotifyIcon.</returns> public static Rectangle?GetNotifyIconRectLegacy(NotifyIcon notifyicon) { Rectangle?nirect = null; FieldInfo idFieldInfo = notifyicon.GetType().GetField("id", BindingFlags.NonPublic | BindingFlags.Instance); int niid = (int)idFieldInfo.GetValue(notifyicon); FieldInfo windowFieldInfo = notifyicon.GetType().GetField("window", BindingFlags.NonPublic | BindingFlags.Instance); System.Windows.Forms.NativeWindow nativeWindow = (System.Windows.Forms.NativeWindow)windowFieldInfo.GetValue(notifyicon); IntPtr nihandle = nativeWindow.Handle; if (nihandle == null || nihandle == IntPtr.Zero) { return(null); } // find the handle of the task bar IntPtr taskbarparenthandle = NativeMethods.FindWindow("Shell_TrayWnd", null); if (taskbarparenthandle == (IntPtr)null) { return(null); } // find the handle of the notification area IntPtr naparenthandle = NativeMethods.FindWindowEx(taskbarparenthandle, IntPtr.Zero, "TrayNotifyWnd", null); if (naparenthandle == (IntPtr)null) { return(null); } // make a list of toolbars in the notification area (one of them should contain the icon) List <IntPtr> natoolbarwindows = NativeMethods.GetChildToolbarWindows(naparenthandle); bool found = false; for (int i = 0; !found && i < natoolbarwindows.Count; i++) { IntPtr natoolbarhandle = natoolbarwindows[i]; // retrieve the number of toolbar buttons (i.e. notify icons) int buttoncount = NativeMethods.SendMessage(natoolbarhandle, NativeMethods.TB_BUTTONCOUNT, IntPtr.Zero, IntPtr.Zero).ToInt32(); // get notification area's process id uint naprocessid; NativeMethods.GetWindowThreadProcessId(natoolbarhandle, out naprocessid); // get handle to notification area's process IntPtr naprocesshandle = NativeMethods.OpenProcess(NativeMethods.ProcessAccessFlags.All, false, naprocessid); if (naprocesshandle == IntPtr.Zero) { return(null); } // allocate enough memory within the notification area's process to store the button info we want IntPtr toolbarmemoryptr = NativeMethods.VirtualAllocEx(naprocesshandle, (IntPtr)null, (uint)Marshal.SizeOf(typeof(NativeMethods.TBBUTTON)), NativeMethods.AllocationType.Commit, NativeMethods.MemoryProtection.ReadWrite); if (toolbarmemoryptr == IntPtr.Zero) { return(null); } try { // loop through the toolbar's buttons until we find our notify icon for (int j = 0; !found && j < buttoncount; j++) { int bytesread = -1; // ask the notification area to give us information about the current button NativeMethods.SendMessage(natoolbarhandle, NativeMethods.TB_GETBUTTON, new IntPtr(j), toolbarmemoryptr); // retrieve that information from the notification area's process NativeMethods.TBBUTTON buttoninfo = new NativeMethods.TBBUTTON(); NativeMethods.ReadProcessMemory(naprocesshandle, toolbarmemoryptr, out buttoninfo, Marshal.SizeOf(buttoninfo), out bytesread); if (bytesread != Marshal.SizeOf(buttoninfo)) { return(null); } if (buttoninfo.dwData == IntPtr.Zero) { return(null); } // the dwData field contains a pointer to information about the notify icon: // the handle of the notify icon (an 4/8 bytes) and the id of the notify icon (4 bytes) IntPtr niinfopointer = buttoninfo.dwData; // read the notify icon handle IntPtr nihandlenew; NativeMethods.ReadProcessMemory(naprocesshandle, niinfopointer, out nihandlenew, Marshal.SizeOf(typeof(IntPtr)), out bytesread); if (bytesread != Marshal.SizeOf(typeof(IntPtr))) { return(null); } // read the notify icon id uint niidnew; NativeMethods.ReadProcessMemory(naprocesshandle, niinfopointer + Marshal.SizeOf(typeof(IntPtr)), out niidnew, Marshal.SizeOf(typeof(uint)), out bytesread); if (bytesread != Marshal.SizeOf(typeof(uint))) { return(null); } // if we've found a match if (nihandlenew == nihandle && niidnew == niid) { // check if the button is hidden: if it is, return the rectangle of the 'show hidden icons' button if ((byte)(buttoninfo.fsState & NativeMethods.TBSTATE_HIDDEN) != 0) { nirect = GetNotifyAreaButtonRectangle(); } else { NativeMethods.RECT result = new NativeMethods.RECT(); // get the relative rectangle of the toolbar button (notify icon) NativeMethods.SendMessage(natoolbarhandle, NativeMethods.TB_GETITEMRECT, new IntPtr(j), toolbarmemoryptr); NativeMethods.ReadProcessMemory(naprocesshandle, toolbarmemoryptr, out result, Marshal.SizeOf(result), out bytesread); if (bytesread != Marshal.SizeOf(result)) { return(null); } // find where the rectangle lies in relation to the screen NativeMethods.MapWindowPoints(natoolbarhandle, (IntPtr)null, ref result, 2); nirect = result; } found = true; } } } finally { // free memory within process NativeMethods.VirtualFreeEx(naprocesshandle, toolbarmemoryptr, 0, NativeMethods.FreeType.Release); // close handle to process NativeMethods.CloseHandle(naprocesshandle); } } return(nirect); }
private static NativeWindow EnsureCreated (NativeWindow window, IntPtr hWnd) { // we need to do this AssignHandle here instead of relying on // Control.WndProc to do it, because subclasses can override // WndProc, install their own WM_CREATE block, and look at // this.Handle, and it needs to be set. Otherwise, we end up // recursively creating windows and emitting WM_CREATE. if (window == null && WindowCreating != null) { window = WindowCreating; WindowCreating = null; if (window.Handle == IntPtr.Zero) window.AssignHandle (hWnd); } return window; }
private static void RemoveFromTable (NativeWindow window) { IntPtr handle = window.Handle; if (handle == IntPtr.Zero) return; lock (window_collection) { object current = window_collection[handle]; if (current != null) { NativeWindow currentWindow = current as NativeWindow; if (currentWindow != null) { window_collection.Remove (handle); } else { // list of windows ArrayList windows = (ArrayList) window_collection[handle]; windows.Remove (window); if (windows.Count == 0) window_collection.Remove (handle); else if (windows.Count == 1) window_collection[handle] = windows[0]; } } } }
internal static Int32 WndProc(Int32 hWnd, Msg msg, Int32 wParam, Int32 lParam) { IntPtr result = IntPtr.Zero; Message m = new Message(); m.HWnd = (IntPtr)hWnd; m.Msg = (int)msg; m.WParam = (IntPtr)wParam; m.LParam = (IntPtr)lParam; m.Result = IntPtr.Zero; #if debug Console.WriteLine("NativeWindow.cs ({0}, {1}, {2}, {3}): result {4}", hWnd, msg, wParam, lParam, m.Result); #endif NativeWindow window = null; try { object current = null; lock (window_collection) { current = window_collection[(IntPtr)hWnd]; } window = current as NativeWindow; if (current == null) { window = EnsureCreated(window, (IntPtr)hWnd); } if (window != null) { window.WndProc(ref m); result = m.Result; } else if (current is ArrayList) { ArrayList windows = (ArrayList)current; lock (windows) { if (windows.Count > 0) { window = EnsureCreated((NativeWindow)windows[0], (IntPtr)hWnd); window.WndProc(ref m); // the first one is the control's one. all others are synthetic, // so we want only the result from the control result = m.Result; for (int i = 1; i < windows.Count; i++) { ((NativeWindow)windows[i]).WndProc(ref m); } } } } else { result = XplatUI.DefWndProc(ref m); } } catch (Exception ex) { #if !ExternalExceptionHandler if (window != null) { if (msg == Msg.WM_PAINT && window is Control.ControlNativeWindow) { // Replace control with a red cross var control = ((Control.ControlNativeWindow)window).Owner; control.Hide(); var redCross = new Control(control.Parent, string.Empty); redCross.BackColor = Color_.White; redCross.ForeColor = Color_.Red; redCross.Bounds = control.Bounds; redCross.Paint += HandleRedCrossPaint; } window.OnThreadException(ex); } #else throw; #endif } #if debug Console.WriteLine("NativeWindow.cs: Message {0}, result {1}", msg, m.Result); #endif return((Int32)result); }
public DialogResult ShowDialog(IWin32Window owner) { if (!SystemInformation.UserInteractive) { throw new InvalidOperationException(SR.CantShowModalOnNonInteractive); } NativeWindow native = null;//This will be used if there is no owner or active window (declared here so it can be kept alive) IntPtr hwndOwner = IntPtr.Zero; DialogResult result = DialogResult.Cancel; try { if (owner != null) { hwndOwner = Control.GetSafeHandle(owner); } if (hwndOwner == IntPtr.Zero) { hwndOwner = UnsafeNativeMethods.GetActiveWindow(); } if (hwndOwner == IntPtr.Zero) { //We will have to create our own Window native = new NativeWindow(); native.CreateHandle(new CreateParams()); hwndOwner = native.Handle; } if (helpMsg == 0) { helpMsg = SafeNativeMethods.RegisterWindowMessage("commdlg_help"); } NativeMethods.WndProc ownerProc = new NativeMethods.WndProc(this.OwnerWndProc); hookedWndProc = System.Runtime.InteropServices.Marshal.GetFunctionPointerForDelegate(ownerProc); System.Diagnostics.Debug.Assert(IntPtr.Zero == defOwnerWndProc, "The previous subclass wasn't properly cleaned up"); IntPtr userCookie = IntPtr.Zero; try { //UnsafeNativeMethods.[Get|Set]WindowLong is smart enough to call SetWindowLongPtr on 64-bit OS defOwnerWndProc = UnsafeNativeMethods.SetWindowLong(new HandleRef(this, hwndOwner), NativeMethods.GWL_WNDPROC, ownerProc); if (Application.UseVisualStyles) { userCookie = UnsafeNativeMethods.ThemingScope.Activate(); } Application.BeginModalMessageLoop(); try { result = RunDialog(hwndOwner) ? DialogResult.OK : DialogResult.Cancel; } finally { Application.EndModalMessageLoop(); } } finally { IntPtr currentSubClass = UnsafeNativeMethods.GetWindowLong(new HandleRef(this, hwndOwner), NativeMethods.GWL_WNDPROC); if (IntPtr.Zero != defOwnerWndProc || currentSubClass != hookedWndProc) { UnsafeNativeMethods.SetWindowLong(new HandleRef(this, hwndOwner), NativeMethods.GWL_WNDPROC, new HandleRef(this, defOwnerWndProc)); } UnsafeNativeMethods.ThemingScope.Deactivate(userCookie); defOwnerWndProc = IntPtr.Zero; hookedWndProc = IntPtr.Zero; //Ensure that the subclass delegate will not be GC collected until after it has been subclassed GC.KeepAlive(ownerProc); } } finally { if (null != native) { native.DestroyHandle(); } } return(result); }
private static void AddWindowToTable(IntPtr handle, NativeWindow window) { lock (internalSyncObject) { uint num; uint num2; if (handleCount >= hashLoadSize) { ExpandTable(); } anyHandleCreated = true; anyHandleCreatedInApp = true; uint num3 = InitHash(handle, hashBuckets.Length, out num, out num2); int num4 = 0; int index = -1; GCHandle handle2 = GCHandle.Alloc(window, GCHandleType.Weak); do { int num6 = (int)(num % hashBuckets.Length); if (((index == -1) && (hashBuckets[num6].handle == new IntPtr(-1))) && (hashBuckets[num6].hash_coll < 0)) { index = num6; } if ((hashBuckets[num6].handle == IntPtr.Zero) || ((hashBuckets[num6].handle == new IntPtr(-1)) && ((hashBuckets[num6].hash_coll & 0x80000000L) == 0L))) { if (index != -1) { num6 = index; } hashBuckets[num6].window = handle2; hashBuckets[num6].handle = handle; hashBuckets[num6].hash_coll |= (int)num3; handleCount++; goto Label_0269; } if (((hashBuckets[num6].hash_coll & 0x7fffffff) == num3) && (handle == hashBuckets[num6].handle)) { GCHandle handle3 = hashBuckets[num6].window; if (handle3.IsAllocated) { window.previousWindow = (NativeWindow)handle3.Target; window.previousWindow.nextWindow = window; handle3.Free(); } hashBuckets[num6].window = handle2; goto Label_0269; } if (index == -1) { hashBuckets[num6].hash_coll |= -2147483648; } num += num2; }while (++num4 < hashBuckets.Length); if (index != -1) { hashBuckets[index].window = handle2; hashBuckets[index].handle = handle; hashBuckets[index].hash_coll |= (int)num3; handleCount++; } Label_0269 :; } }
public DialogResult ShowDialog(IWin32Window owner) { System.Windows.Forms.IntSecurity.SafeSubWindows.Demand(); if (!SystemInformation.UserInteractive) { throw new InvalidOperationException(System.Windows.Forms.SR.GetString("CantShowModalOnNonInteractive")); } NativeWindow window = null; IntPtr zero = IntPtr.Zero; DialogResult cancel = DialogResult.Cancel; try { if (owner != null) { zero = Control.GetSafeHandle(owner); } if (zero == IntPtr.Zero) { zero = System.Windows.Forms.UnsafeNativeMethods.GetActiveWindow(); } if (zero == IntPtr.Zero) { window = new NativeWindow(); window.CreateHandle(new CreateParams()); zero = window.Handle; } if (helpMsg == 0) { helpMsg = System.Windows.Forms.SafeNativeMethods.RegisterWindowMessage("commdlg_help"); } System.Windows.Forms.NativeMethods.WndProc d = new System.Windows.Forms.NativeMethods.WndProc(this.OwnerWndProc); this.hookedWndProc = Marshal.GetFunctionPointerForDelegate(d); IntPtr userCookie = IntPtr.Zero; try { this.defOwnerWndProc = System.Windows.Forms.UnsafeNativeMethods.SetWindowLong(new HandleRef(this, zero), -4, d); if (Application.UseVisualStyles) { userCookie = System.Windows.Forms.UnsafeNativeMethods.ThemingScope.Activate(); } Application.BeginModalMessageLoop(); try { cancel = this.RunDialog(zero) ? DialogResult.OK : DialogResult.Cancel; } finally { Application.EndModalMessageLoop(); } return(cancel); } finally { IntPtr windowLong = System.Windows.Forms.UnsafeNativeMethods.GetWindowLong(new HandleRef(this, zero), -4); if ((IntPtr.Zero != this.defOwnerWndProc) || (windowLong != this.hookedWndProc)) { System.Windows.Forms.UnsafeNativeMethods.SetWindowLong(new HandleRef(this, zero), -4, new HandleRef(this, this.defOwnerWndProc)); } System.Windows.Forms.UnsafeNativeMethods.ThemingScope.Deactivate(userCookie); this.defOwnerWndProc = IntPtr.Zero; this.hookedWndProc = IntPtr.Zero; GC.KeepAlive(d); } } finally { if (window != null) { window.DestroyHandle(); } } return(cancel); }
public void Destroy() { this.tipWindow.DestroyHandle(); this.tipWindow = null; }
/// <summary> /// Constructs a new instance of the CopyDataChannels collection. /// Automatically managed by the CopyData class. /// </summary> /// <param name="owner">The NativeWindow this collection /// will be associated with</param> internal CopyDataChannels(NativeWindow owner) { this.owner = owner; }
//============================================================== /// <summary> /// 通过向指定的按键发送KeyUp来恢复状态 /// </summary> /// <param name="c"></param> /// <param name="allKeys"></param> public static void TryResetKeys(params IEnumerable<VirtualKeyCode>[] allKeys) { var dummyWnd = new NativeWindow(); try { //如果被系统或者杀毒软件阻止, 则发送给自己的一个窗口,这样避免被在此拦截。 dummyWnd.CreateHandle(new CreateParams(){ExStyle = (int) (User32.WS_EX.WS_EX_LAYERED | User32.WS_EX.WS_EX_TOOLWINDOW)}); User32.ShowWindow(dummyWnd.Handle, User32.SW.SW_SHOWNORMAL); var sim = new InputSimulator(); sim.Keyboard.Sleep(10); foreach (var keys in allKeys) { foreach (var k in keys) { User32.SetForegroundWindow(dummyWnd.Handle); sim.Keyboard.KeyUp(k); } } } catch (Exception) { Debug.WriteLine("恢复键盘状态失败"); #if TEST throw; #endif } finally { dummyWnd.DestroyHandle(); } }
/// <summary> /// This function is the callback used to execute a command when the a menu item is clicked. /// See the Initialize method to see how the menu item is associated to this function using /// the OleMenuCommandService service and the MenuCommand class. /// </summary> private void MenuItemCallback(object sender, EventArgs e) { // Show a Message Box to prove we were here EnvDTE.DTE dte = (EnvDTE.DTE)GetService(typeof(EnvDTE.DTE)); IVsUIShell uiShell = (IVsUIShell)GetService(typeof(SVsUIShell)); Guid clsid = Guid.Empty; IntPtr parentHwnd = IntPtr.Zero; uiShell.GetDialogOwnerHwnd(out parentHwnd); NativeWindow parentShim = new NativeWindow(); parentShim.AssignHandle(parentHwnd); AttachDialog dialog = new AttachDialog(); DialogResult result = dialog.ShowDialog(parentShim); if (result == DialogResult.OK) { foreach (int selected_id in dialog.SelectedItems) { foreach (EnvDTE90a.Process4 p in dte.Debugger.LocalProcesses) { System.Diagnostics.Debug.WriteLine("Found process {0}", p.ProcessID); if (p.ProcessID != selected_id) continue; p.Attach(); System.Diagnostics.Debug.WriteLine("Attaching to process successful."); break; } } } }
private static bool IsRootWindowInListWithChildren(NativeWindow window) { return ((window.PreviousWindow != null) && (window.nextWindow == null)); }
private static bool IsRootWindowInListWithChildren(NativeWindow window) { return((window.PreviousWindow != null) && (window.nextWindow == null)); }
private static void RemoveWindowFromTable(IntPtr handle, NativeWindow window) { lock (internalSyncObject) { uint num; uint num2; int num5; uint num3 = InitHash(handle, hashBuckets.Length, out num, out num2); int num4 = 0; NativeWindow previousWindow = window.PreviousWindow; do { num5 = (int) (num % hashBuckets.Length); HandleBucket bucket = hashBuckets[num5]; if (((bucket.hash_coll & 0x7fffffff) == num3) && (handle == bucket.handle)) { bool flag = window.nextWindow == null; bool flag2 = IsRootWindowInListWithChildren(window); if (window.previousWindow != null) { window.previousWindow.nextWindow = window.nextWindow; } if (window.nextWindow != null) { window.nextWindow.defWindowProc = window.defWindowProc; window.nextWindow.previousWindow = window.previousWindow; } window.nextWindow = null; window.previousWindow = null; if (flag2) { if (hashBuckets[num5].window.IsAllocated) { hashBuckets[num5].window.Free(); } hashBuckets[num5].window = GCHandle.Alloc(previousWindow, GCHandleType.Weak); } else if (flag) { hashBuckets[num5].hash_coll &= -2147483648; if (hashBuckets[num5].hash_coll != 0) { hashBuckets[num5].handle = new IntPtr(-1); } else { hashBuckets[num5].handle = IntPtr.Zero; } if (hashBuckets[num5].window.IsAllocated) { hashBuckets[num5].window.Free(); } handleCount--; } break; } num += num2; } while ((hashBuckets[num5].hash_coll < 0) && (++num4 < hashBuckets.Length)); } }
public DialogResult ShowDialog(IWin32Window owner) { DialogResult returnDialogResult = DialogResult.Cancel; if(this.IsDisposed) return returnDialogResult; if (FileDlgType == FileDialogType.OpenFileDlg) { _dlgWrapper = new DialogWrapper<OpenFileDialog>(this); } else { _dlgWrapper = new DialogWrapper<SaveFileDialog>(this); } OnPrepareMSDialog(); if(!_hasRunInitMSDialog) InitMSDialog(); try { returnDialogResult = _MSdialog.ShowDialog(owner); } // Sometimes if you open a animated .gif on the preview and the Form is closed, .Net class throw an exception // Lets ignore this exception and keep closing the form. catch (ObjectDisposedException) { } catch (Exception ex) { MessageBox.Show("unable to get the modal dialog handle", ex.Message); } return returnDialogResult; }
public virtual void CreateHandle(CreateParams cp) { lock (this) { CheckReleased(); WindowClass windowClass = WindowClass.Create(cp.ClassName, (User32.CS)cp.ClassStyle); lock (s_createWindowSyncObject) { // The CLR will sometimes pump messages while we're waiting on the lock. // If a message comes through (say a WM_ACTIVATE for the parent) which // causes the handle to be created, we can try to create the handle twice // for NativeWindow. Check the handle again to avoid this. if (Handle != IntPtr.Zero) { return; } IntPtr createResult = IntPtr.Zero; int lastWin32Error = 0; NativeWindow prevTargetWindow = windowClass._targetWindow; try { windowClass._targetWindow = this; // Parking window dpi awareness context need to match with dpi awareness context of control being // parented to this parking window. Otherwise, reparenting of control will fail. using (DpiHelper.EnterDpiAwarenessScope(DpiAwarenessContext)) { IntPtr modHandle = Kernel32.GetModuleHandleW(null); // Older versions of Windows AV rather than returning E_OUTOFMEMORY. // Catch this and then we re-throw an out of memory error. try { // CreateWindowEx throws if WindowText is greater than the max // length of a 16 bit int (32767). // If it exceeds the max, we should take the substring.... if (cp.Caption != null && cp.Caption.Length > short.MaxValue) { cp.Caption = cp.Caption.Substring(0, short.MaxValue); } createResult = User32.CreateWindowExW( (User32.WS_EX)cp.ExStyle, windowClass._windowClassName, cp.Caption, (User32.WS)cp.Style, cp.X, cp.Y, cp.Width, cp.Height, cp.Parent, IntPtr.Zero, modHandle, cp.Param); lastWin32Error = Marshal.GetLastWin32Error(); } catch (NullReferenceException e) { throw new OutOfMemoryException(SR.ErrorCreatingHandle, e); } } } finally { windowClass._targetWindow = prevTargetWindow; } Debug.WriteLineIf(CoreSwitches.PerfTrack.Enabled, "Handle created of type '" + cp.ClassName + "' with caption '" + cp.Caption + "' from NativeWindow of type '" + GetType().FullName + "'"); if (createResult == IntPtr.Zero) { throw new Win32Exception(lastWin32Error, SR.ErrorCreatingHandle); } _ownHandle = true; } } }
public virtual void CreateHandle(CreateParams cp) { if (cp != null) { WindowCreating = this; window_handle=XplatUI.CreateWindow(cp); WindowCreating = null; if (window_handle != IntPtr.Zero) AddToTable (this); } }
internal static IntPtr WndProc(IntPtr hWnd, Msg msg, IntPtr wParam, IntPtr lParam) { IntPtr result = IntPtr.Zero; Message m = new Message(); m.HWnd = hWnd; m.Msg = (int)msg; m.WParam = wParam; m.LParam = lParam; m.Result = IntPtr.Zero; #if debug Console.WriteLine("NativeWindow.cs ({0}, {1}, {2}, {3}): result {4}", hWnd, msg, wParam, lParam, m.Result); #endif NativeWindow window = null; try { object current = null; lock (window_collection) { current = window_collection[hWnd]; } window = current as NativeWindow; if (current == null) { window = EnsureCreated(window, hWnd); } if (window != null) { window.WndProc(ref m); result = m.Result; } else if (current is ArrayList) { ArrayList windows = (ArrayList)current; lock (windows) { if (windows.Count > 0) { window = EnsureCreated((NativeWindow)windows[0], hWnd); window.WndProc(ref m); // the first one is the control's one. all others are synthetic, // so we want only the result from the control result = m.Result; for (int i = 1; i < windows.Count; i++) { ((NativeWindow)windows[i]).WndProc(ref m); } } } } else { result = XplatUI.DefWndProc(ref m); } } catch (Exception ex) { #if !ExternalExceptionHandler if (window != null) { window.OnThreadException(ex); } #else throw; #endif } #if debug Console.WriteLine("NativeWindow.cs: Message {0}, result {1}", msg, m.Result); #endif return(result); }
private static void AddToTable (NativeWindow window) { IntPtr handle = window.Handle; if (handle == IntPtr.Zero) return; lock (window_collection) { object current = window_collection[handle]; if (current == null) { window_collection.Add (handle, window); } else { NativeWindow currentWindow = current as NativeWindow; if (currentWindow != null) { if (currentWindow != window) { ArrayList windows = new ArrayList (); windows.Add (currentWindow); windows.Add (window); window_collection[handle] = windows; } } else { // list of windows ArrayList windows = (ArrayList) window_collection[handle]; if (!windows.Contains (window)) windows.Add (window); } } } }
private void Window_Loaded(object sender, RoutedEventArgs e) { win32Window = new Win32Forms.NativeWindow(); win32Window.AssignHandle((new WindowInteropHelper(this)).Handle); }