Ejemplo n.º 1
0
        static CommunicationWindowManager()
        {
            string windowClassName = string.Empty;

            for (int i = 0; true; i++)
            {
                windowClassName = WindowClassNameBase + i;

                //ウィンドウプロックをGCの対象から外すためにstaticメンバにする
                MyWindowProc = new NativeMethods.WndProc(WndProc);

                //ウィンドウクラス登録
                NativeMethods.WNDCLASSEX wc = new NativeMethods.WNDCLASSEX();
                wc.cbSize        = (uint)Marshal.SizeOf(wc);
                wc.style         = 0;
                wc.lpfnWndProc   = Marshal.GetFunctionPointerForDelegate(MyWindowProc);
                wc.cbClsExtra    = 0;
                wc.cbWndExtra    = 0;
                wc.hInstance     = NativeMethods.GetModuleHandle(null);
                wc.hIcon         = IntPtr.Zero;
                wc.hCursor       = IntPtr.Zero;
                wc.hbrBackground = IntPtr.Zero;
                wc.lpszMenuName  = string.Empty;
                wc.lpszClassName = windowClassName;
                wc.hIconSm       = IntPtr.Zero;
                if (NativeMethods.RegisterClassEx(ref wc) != 0)
                {
                    break;
                }
            }
            WindowClassName = windowClassName;
        }
Ejemplo n.º 2
0
        // Helpers

        // create a window to handle messages
        static IntPtr CreateTestWindow()
        {
            // Create a simple Win32 window
            var hwndStatic = NativeMethods.CreateWindowEx(0, "Static", String.Empty, NativeMethods.WS_POPUP,
                                                          0, 0, 0, 0, NativeMethods.HWND_MESSAGE, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);

            // subclass it with a custom WndProc
            IntPtr prevWndProc = IntPtr.Zero;

            NativeMethods.WndProc newWndProc = (hwnd, msg, wParam, lParam) =>
            {
                if (msg == NativeMethods.WM_TEST)
                {
                    Console.WriteLine("WM_TEST processed: " + wParam);
                }
                return(NativeMethods.CallWindowProc(prevWndProc, hwnd, msg, wParam, lParam));
            };

            prevWndProc = NativeMethods.SetWindowLong(hwndStatic, NativeMethods.GWL_WNDPROC,
                                                      Marshal.GetFunctionPointerForDelegate(newWndProc));
            if (prevWndProc == IntPtr.Zero)
            {
                throw new ApplicationException();
            }

            return(hwndStatic);
        }
Ejemplo n.º 3
0
 public static IntPtr SetWindowLong(HandleRef hWnd, int nIndex, NativeMethods.WndProc wndproc)
 {
     if (IntPtr.Size == 4)
     {
         return(SetWindowLongPtr32(hWnd, nIndex, wndproc));
     }
     return(SetWindowLongPtr64(hWnd, nIndex, wndproc));
 }
Ejemplo n.º 4
0
        /// <include file='doc\FileDialog.uex' path='docs/doc[@for="FileDialog.RunDialog"]/*' />
        /// <devdoc>
        ///    Implements running of a file dialog.
        /// </devdoc>
        /// <internalonly/>
        protected override bool RunDialog(IntPtr hWndOwner)
        {
            NativeMethods.WndProc        hookProcPtr = new NativeMethods.WndProc(this.HookProc);
            NativeMethods.OPENFILENAME_I ofn         = new NativeMethods.OPENFILENAME_I();
            try {
                charBuffer = CharBuffer.CreateBuffer(FILEBUFSIZE);
                if (fileNames != null)
                {
                    charBuffer.PutString(fileNames[0]);
                }
                ofn.lStructSize = Marshal.SizeOf(typeof(NativeMethods.OPENFILENAME_I));

                // SECREVIEW : Assert environment so that we can determine
                //           : the platform that we are running on. We only
                //           : use the information to change the style of
                //           : dialog, so it is safe.
                //
                IntSecurity.UnrestrictedEnvironment.Assert();
                try {
                    // Degrade to the older style dialog if we're not on Win2K.
                    // We do this by setting the struct size to a different value
                    //
                    if (Environment.OSVersion.Platform != System.PlatformID.Win32NT ||
                        Environment.OSVersion.Version.Major < 5)
                    {
                        ofn.lStructSize = 0x4C;
                    }
                }
                finally {
                    CodeAccessPermission.RevertAssert();
                }

                ofn.hwndOwner       = hWndOwner;
                ofn.hInstance       = Instance;
                ofn.lpstrFilter     = MakeFilterString(filter);
                ofn.nFilterIndex    = filterIndex;
                ofn.lpstrFile       = charBuffer.AllocCoTaskMem();
                ofn.nMaxFile        = FILEBUFSIZE;
                ofn.lpstrInitialDir = initialDir;
                ofn.lpstrTitle      = title;
                ofn.Flags           = Options | (NativeMethods.OFN_EXPLORER | NativeMethods.OFN_ENABLEHOOK | NativeMethods.OFN_ENABLESIZING);
                ofn.lpfnHook        = hookProcPtr;
                ofn.FlagsEx         = NativeMethods.OFN_USESHELLITEM;
                if (defaultExt != null && AddExtension)
                {
                    ofn.lpstrDefExt = defaultExt;
                }
                return(RunFileDialog(ofn));
            }
            finally {
                charBuffer = null;
                if (ofn.lpstrFile != IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(ofn.lpstrFile);
                }
            }
        }
Ejemplo n.º 5
0
        public override void Start()
        {
            //https://stackoverflow.com/questions/8980873/implementing-a-win32-message-loop-and-creating-a-window-object-with-p-invoke
            _messageWindowProc = WndProc;
            w = new WNDCLASSEX
            {
                cbSize        = (uint)Marshal.SizeOf(typeof(WNDCLASSEX)),
                lpszClassName = "OTB_Message_Watcher_Class",
                lpfnWndProc   = _messageWindowProc
            };

            NativeMethods.RegisterClassEx(ref w);
            IntPtr hInstance = NativeMethods.GetModuleHandle(Process.GetCurrentProcess().MainModule.ModuleName);

            //new IntPtr(-3) = MESSAGE ONLY
            _messageWindowHandle = NativeMethods.CreateWindowEx(0, w.lpszClassName, w.lpszClassName, 0, 0, 0, 0, 0, new IntPtr(-3), IntPtr.Zero, hInstance /*Can I make this 0?*/, IntPtr.Zero);
            NativeMethods.AddClipboardFormatListener(_messageWindowHandle);


            _windowsMouseHookHandle = IntPtr.Zero;
            _user32LibraryHandle    = IntPtr.Zero;
            _mouseHookProc          = LowLevelMouseProc; // we must keep alive _hookProc, because GC is not aware about SetWindowsHookEx behaviour.

            _windowsKeyboardHookHandle = IntPtr.Zero;
            _keyboardHookProc          = LowLevelKeyboardProc; // we must keep alive _hookProc, because GC is not aware about SetWindowsHookEx behaviour.


            _user32LibraryHandle = NativeMethods.LoadLibrary("User32");
            if (_user32LibraryHandle == IntPtr.Zero)
            {
                int errorCode = Marshal.GetLastWin32Error();
                throw new Win32Exception(errorCode, $"Failed to load library 'User32.dll'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
            }

            _windowsMouseHookHandle = NativeMethods.SetWindowsHookEx(WH_MOUSE_LL, _mouseHookProc, _user32LibraryHandle, 0);
            if (_windowsMouseHookHandle == IntPtr.Zero)
            {
                int errorCode = Marshal.GetLastWin32Error();
                throw new Win32Exception(errorCode, $"Failed to adjust mouse hooks for '{Process.GetCurrentProcess().ProcessName}'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
            }

            _windowsKeyboardHookHandle = NativeMethods.SetWindowsHookEx(WH_KEYBOARD_LL, _keyboardHookProc, _user32LibraryHandle, 0);
            if (_windowsKeyboardHookHandle == IntPtr.Zero)
            {
                int errorCode = Marshal.GetLastWin32Error();
                throw new Win32Exception(errorCode, $"Failed to adjust keyboard hooks for '{Process.GetCurrentProcess().ProcessName}'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
            }

            //init initial cursor position
            if (NativeMethods.GetCursorPos(out Point p))
            {
                MouseState.Position = new MousePoint(p.X, p.Y);
            }
        }
Ejemplo n.º 6
0
        private void HookWindowProc(IntPtr hwnd, NativeMethods.WndProc newWndProc, IntPtr oldWndProc)
        {
            _hwndAttached  = hwnd;
            _hwndHandleRef = new HandleRef(null, _hwndAttached);
            _bond          = Bond.Attached;

            _attachedWndProc = newWndProc;
            _oldWndProc      = oldWndProc;
            IntPtr oldWndProc2 = (IntPtr)UnsafeNativeMethods.CriticalSetWindowLong(_hwndHandleRef, NativeMethods.GWL_WNDPROC, _attachedWndProc);

            // Track this window so that we can rip out the managed window proc
            // when the CLR shuts down.
            ManagedWndProcTracker.TrackHwndSubclass(this, _hwndAttached);
        }
Ejemplo n.º 7
0
        /// <include file='doc\CommonDialog.uex' path='docs/doc[@for="CommonDialog.ShowDialog1"]/*' />
        /// <devdoc>
        ///    <para>
        ///       Runs a common dialog box, parented to the given IWin32Window.
        ///    </para>
        /// </devdoc>
        public DialogResult ShowDialog(IWin32Window owner)
        {
            IntSecurity.SafeSubWindows.Demand();

            if (owner == null || owner.Handle == IntPtr.Zero)
            {
                return(ShowDialog());
            }

            if (!SystemInformation.UserInteractive)
            {
                throw new InvalidOperationException(SR.GetString(SR.CantShowModalOnNonInteractive));
            }

            if (helpMsg == 0)
            {
                helpMsg = SafeNativeMethods.RegisterWindowMessage("commdlg_help");
            }

            IntPtr hwndOwner = owner.Handle;

            defOwnerWndProc = UnsafeNativeMethods.GetWindowLong(new HandleRef(owner, hwndOwner), NativeMethods.GWL_WNDPROC);

            // define ownerproc out here so it won't be garbage collected before the finally
            // clause runs
            NativeMethods.WndProc ownerProc = new NativeMethods.WndProc(this.OwnerWndProc);
            DialogResult          result    = DialogResult.Cancel;

            try {
                UnsafeNativeMethods.SetWindowLong(new HandleRef(owner, hwndOwner), NativeMethods.GWL_WNDPROC, ownerProc);

                Application.BeginModalMessageLoop();
                try {
                    result = RunDialog(hwndOwner) ? DialogResult.OK : DialogResult.Cancel;
                    GC.KeepAlive(ownerProc);
                }
                finally {
                    Application.EndModalMessageLoop();
                }
            }
            finally {
                if (UnsafeNativeMethods.IsWindow(new HandleRef(owner, hwndOwner)))
                {
                    UnsafeNativeMethods.SetWindowLong(new HandleRef(owner, hwndOwner), NativeMethods.GWL_WNDPROC, new HandleRef(null, defOwnerWndProc));
                }
            }

            return(result);
        }
Ejemplo n.º 8
0
        protected override bool RunDialog(IntPtr hwndOwner)
        {
            var hookProcPtr = new NativeMethods.WndProc(HookProc);

            if (!UseEXDialog)
            {
                NativeMethods.PRINTDLG data = CreatePRINTDLG();
                return(ShowPrintDialog(hwndOwner, hookProcPtr, data));
            }
            else
            {
                NativeMethods.PRINTDLGEX data = CreatePRINTDLGEX();
                return(ShowPrintDialog(hwndOwner, data));
            }
        }
Ejemplo n.º 9
0
        private void CreateWindow()
        {
            this.m_proc = new NativeMethods.WndProc(this.CustomProc);

            var wndClass			= new NativeMethods.WNDCLASS();
            wndClass.lpszClassName	= this.m_uniqueName;
            wndClass.lpfnWndProc	= Marshal.GetFunctionPointerForDelegate(this.m_proc);

            var resRegister	= NativeMethods.RegisterClass(ref wndClass);
            var resError	= Marshal.GetLastWin32Error();

            if (resRegister == 0 && resError != NativeMethods.ERROR_CLASS_ALREADY_EXISTS)
                throw new Exception();

            this.m_customHwnd = NativeMethods.CreateWindowEx(0, this.m_uniqueName, null, 0, 0, 0, 0, 0, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
        }
Ejemplo n.º 10
0
            /// <summary>Create a window class for the win32 window</summary>
            /// <param name="className">Name of the window class.</param>
            public WindowClass(string className)
            {
                defWindowProc = new NativeMethods.WndProc(NativeMethods.DefWindowProc);

                var wndclass = default(WNDCLASS);

                wndclass.cbClsExtra    = 0;
                wndclass.cbWndExtra    = 0;
                wndclass.hbrBackground = IntPtr.Zero;
                wndclass.hCursor       = IntPtr.Zero;
                wndclass.hIcon         = IntPtr.Zero;
                wndclass.lpfnWndProc   = defWindowProc;
                wndclass.lpszClassName = className;
                wndclass.lpszMenuName  = null;
                wndclass.style         = 0u;
                hWndClass = new IntPtr(NativeMethods.RegisterClass(ref wndclass));
            }             // ctor
Ejemplo n.º 11
0
 private bool RunDialogOld(IntPtr hWndOwner)
 {
     NativeMethods.WndProc        hookProcPtr = new NativeMethods.WndProc(this.HookProc);
     NativeMethods.OPENFILENAME_I ofn         = new NativeMethods.OPENFILENAME_I();
     try {
         charBuffer = CharBuffer.CreateBuffer(FILEBUFSIZE);
         if (fileNames != null)
         {
             charBuffer.PutString(fileNames[0]);
         }
         ofn.lStructSize = Marshal.SizeOf(typeof(NativeMethods.OPENFILENAME_I));
         // Degrade to the older style dialog if we're not on Win2K.
         // We do this by setting the struct size to a different value
         //
         if (Environment.OSVersion.Platform != System.PlatformID.Win32NT ||
             Environment.OSVersion.Version.Major < 5)
         {
             ofn.lStructSize = 0x4C;
         }
         ofn.hwndOwner       = hWndOwner;
         ofn.hInstance       = Instance;
         ofn.lpstrFilter     = MakeFilterString(filter, this.DereferenceLinks);
         ofn.nFilterIndex    = filterIndex;
         ofn.lpstrFile       = charBuffer.AllocCoTaskMem();
         ofn.nMaxFile        = FILEBUFSIZE;
         ofn.lpstrInitialDir = initialDir;
         ofn.lpstrTitle      = title;
         ofn.Flags           = Options | (NativeMethods.OFN_EXPLORER | NativeMethods.OFN_ENABLEHOOK | NativeMethods.OFN_ENABLESIZING);
         ofn.lpfnHook        = hookProcPtr;
         ofn.FlagsEx         = NativeMethods.OFN_USESHELLITEM;
         if (defaultExt != null && AddExtension)
         {
             ofn.lpstrDefExt = defaultExt;
         }
         //Security checks happen here
         return(RunFileDialog(ofn));
     }
     finally {
         charBuffer = null;
         if (ofn.lpstrFile != IntPtr.Zero)
         {
             Marshal.FreeCoTaskMem(ofn.lpstrFile);
         }
     }
 }
Ejemplo n.º 12
0
        /// <summary>
        /// 実行。
        /// </summary>
        /// <param name="targetThreadWindowHandle">処理を実行させるウィンドウ。</param>
        /// <param name="action">処理。</param>
        /// <returns>成否。</returns>
        internal static bool Execute(IntPtr targetThreadWindowHandle, MethodInvoker action)
        {
            //現在のウィンドウプロックを取得
            IntPtr currentProc = NativeMethods.GetWindowLongPtr(targetThreadWindowHandle, NativeMethods.GWL_WNDPROC);
            //InvokeWindowを起動するためのプロックを設定
            bool executed = false;

            NativeMethods.WndProc proc = delegate(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam)
            {
                switch (msg)
                {
                case 0:
                    if (!executed)
                    {
                        action();
                        executed = true;
                    }
                    break;

                default:
                    break;
                }
                return(NativeMethods.CallWindowProc(currentProc, hwnd, msg, wParam, lParam));
            };
            NativeMethods.SetWindowLongPtr(targetThreadWindowHandle, NativeMethods.GWL_WNDPROC, Marshal.GetFunctionPointerForDelegate(proc));

            //実行完了待ち
            while (!executed)
            {
                //指定のウィンドウが消えていたら終了
                if (!NativeMethods.IsWindow(targetThreadWindowHandle))
                {
                    return(false);
                }
                NativeMethods.SendMessage(targetThreadWindowHandle, 0, IntPtr.Zero, IntPtr.Zero);
                Thread.Sleep(10);
            }
            GC.KeepAlive(proc);
            GC.KeepAlive(action);

            //元に戻す
            NativeMethods.SetWindowLongPtr(targetThreadWindowHandle, NativeMethods.GWL_WNDPROC, currentProc);
            return(true);
        }
Ejemplo n.º 13
0
        internal IntPtr CriticalAttach(IntPtr hwnd)
        {
            if (hwnd == IntPtr.Zero)
            {
                throw new ArgumentNullException("hwnd");
            }
            if (_bond != Bond.Unattached)
            {
                throw new InvalidOperationException();
            }

            NativeMethods.WndProc newWndProc = new NativeMethods.WndProc(SubclassWndProc);
            IntPtr oldWndProc = UnsafeNativeMethods.GetWindowLongPtr(new HandleRef(this, hwnd), NativeMethods.GWL_WNDPROC);

            HookWindowProc(hwnd, newWndProc, oldWndProc);

            // Return the GC handle as a unique identifier of this
            return((IntPtr)_gcHandle);
        }
Ejemplo n.º 14
0
        private void CreateWindow()
        {
            this.m_proc = new NativeMethods.WndProc(this.CustomProc);

            var wndClass = new NativeMethods.WNDCLASS();

            wndClass.lpszClassName = this.m_uniqueName;
            wndClass.lpfnWndProc   = Marshal.GetFunctionPointerForDelegate(this.m_proc);

            var resRegister = NativeMethods.RegisterClass(ref wndClass);
            var resError    = Marshal.GetLastWin32Error();

            if (resRegister == 0 && resError != NativeMethods.ERROR_CLASS_ALREADY_EXISTS)
            {
                throw new Exception();
            }

            this.m_customHwnd = NativeMethods.CreateWindowEx(0, this.m_uniqueName, null, 0, 0, 0, 0, 0, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
        }
Ejemplo n.º 15
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            if (handle == IntPtr.Zero)
            {
                handle     = new WindowInteropHelper(this).Handle;
                newWndProc = new NativeMethods.WndProc(WindowProc);
                oldWndProc = NativeMethods.GetWindowLongPtr(handle, NativeMethods.GWLP_WNDPROC);
                NativeMethods.SetWindowLongPtr(handle, NativeMethods.GWLP_WNDPROC,
                                               Marshal.GetFunctionPointerForDelegate(newWndProc));
            }

            if (comboBox1.Items.Count == 0 && conf.Configurations.Count > 0)
            {
                for (int i = 0; i < conf.Configurations.Count; i++)
                {
                    var h = conf.Configurations.ElementAt(i);
                    h.Value.PropertyChanged += Header_PropertyChanged;
                    comboBox1.Items.Add(h.Key);

                    var m = h.Value.Modules as Modules;
                    m.PropertyChanged += Modules_PropertyChanged;
                }

                comboBox1.SelectedIndex = 0;
            }
            else
            {
                UpdateStateToControls();
            }

            menuItem2_1.IsEnabled = false;
            menuItem2_2.IsEnabled = false;
            menuItem3_1.IsEnabled = false;
            menuItem3_2.IsEnabled = false;

            button2_1.IsEnabled = false;
            button2_2.IsEnabled = false;
            button3_1.IsEnabled = false;
            button3_2.IsEnabled = false;

            propertyGrid.PropertyValueChanged += Translator_PropertyValueChanged;
        }
Ejemplo n.º 16
0
        protected override bool RunDialog(IntPtr hwndOwner)
        {
            NativeMethods.WndProc     hookProcPtr = new NativeMethods.WndProc(HookProc);
            NativeMethods.CHOOSECOLOR cc          = new NativeMethods.CHOOSECOLOR();
            IntPtr custColorPtr = Marshal.AllocCoTaskMem(64);

            try
            {
                Marshal.Copy(customColors, 0, custColorPtr, 16);
                cc.hwndOwner    = hwndOwner;
                cc.hInstance    = Instance;
                cc.rgbResult    = ColorTranslator.ToWin32(color);
                cc.lpCustColors = custColorPtr;

                int flags = Options | (NativeMethods.CC_RGBINIT | NativeMethods.CC_ENABLEHOOK);
                // Our docs say AllowFullOpen takes precedence over FullOpen; ChooseColor implements the opposite
                if (!AllowFullOpen)
                {
                    flags &= ~NativeMethods.CC_FULLOPEN;
                }

                cc.Flags = flags;

                cc.lpfnHook = hookProcPtr;
                if (!SafeNativeMethods.ChooseColor(cc))
                {
                    return(false);
                }

                if (cc.rgbResult != ColorTranslator.ToWin32(color))
                {
                    color = ColorTranslator.FromOle(cc.rgbResult);
                }

                Marshal.Copy(custColorPtr, customColors, 0, 16);
                return(true);
            }
            finally
            {
                Marshal.FreeCoTaskMem(custColorPtr);
            }
        }
Ejemplo n.º 17
0
        /// <include file='doc\PrintDialog.uex' path='docs/doc[@for="PrintDialog.RunDialog"]/*' />
        /// <devdoc>
        /// </devdoc>
        /// <internalonly/>
        // Use PrintDlgEx and PRINTDLGEX on Win2k and newer OS'.
        protected override bool RunDialog(IntPtr hwndOwner)
        {
            bool returnValue = false;

            NativeMethods.WndProc hookProcPtr = new NativeMethods.WndProc(this.HookProc);

            if (!UseEXDialog || (Environment.OSVersion.Platform != System.PlatformID.Win32NT ||
                                 Environment.OSVersion.Version.Major < 5))
            {
                NativeMethods.PRINTDLG data = CreatePRINTDLG();
                returnValue = ShowPrintDialog(hwndOwner, hookProcPtr, data);
            }
            else
            {
                NativeMethods.PRINTDLGEX data = CreatePRINTDLGEX();
                returnValue = ShowPrintDialog(hwndOwner, data);
            }

            return(returnValue);
        }
Ejemplo n.º 18
0
        private bool RunLegacyDialog(IntPtr hwndOwner)
        {
            NativeMethods.WndProc        lpfnHook       = new NativeMethods.WndProc(this.HookProc);
            NativeMethods.OPENFILENAME_I openfilename_I = new NativeMethods.OPENFILENAME_I();
            bool result;

            try
            {
                this._charBuffer = NativeMethods.CharBuffer.CreateBuffer(8192);
                if (this._fileNames != null)
                {
                    this._charBuffer.PutString(this._fileNames[0]);
                }
                openfilename_I.lStructSize     = Marshal.SizeOf(typeof(NativeMethods.OPENFILENAME_I));
                openfilename_I.hwndOwner       = hwndOwner;
                openfilename_I.hInstance       = IntPtr.Zero;
                openfilename_I.lpstrFilter     = FileDialog.MakeFilterString(this._filter, this.DereferenceLinks);
                openfilename_I.nFilterIndex    = this._filterIndex;
                openfilename_I.lpstrFile       = this._charBuffer.AllocCoTaskMem();
                openfilename_I.nMaxFile        = this._charBuffer.Length;
                openfilename_I.lpstrInitialDir = this._initialDirectory.Value;
                openfilename_I.lpstrTitle      = this._title.Value;
                openfilename_I.Flags           = (this.Options | 8912928);
                openfilename_I.lpfnHook        = lpfnHook;
                openfilename_I.FlagsEx         = 16777216;
                if (this._defaultExtension != null && this.AddExtension)
                {
                    openfilename_I.lpstrDefExt = this._defaultExtension;
                }
                result = this.RunFileDialog(openfilename_I);
            }
            finally
            {
                this._charBuffer = null;
                if (openfilename_I.lpstrFile != IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(openfilename_I.lpstrFile);
                }
            }
            return(result);
        }
Ejemplo n.º 19
0
        protected ushort RegisterClass(string className)
        {
            WNDCLASS wNDCLAss = new WNDCLASS()
            {
                cbClsExtra    = 0,
                cbWndExtra    = 0,
                hbrBackground = IntPtr.Zero,
                hCursor       = IntPtr.Zero,
                hIcon         = IntPtr.Zero
            };
            HwndWrapper hwndWrapper = this;

            NativeMethods.WndProc wndProc = new NativeMethods.WndProc(hwndWrapper.WndProc);
            Delegate @delegate            = wndProc;

            this.wndProc           = wndProc;
            wNDCLAss.lpfnWndProc   = @delegate;
            wNDCLAss.lpszClassName = className;
            wNDCLAss.lpszMenuName  = null;
            wNDCLAss.style         = 0;
            return(NativeMethods.RegisterClass(ref wNDCLAss));
        }
Ejemplo n.º 20
0
 private void DestroyResources()
 {
     if (_dt != null)
     {
         _dt.Stop();
         _dt = null;
     }
     if (_hwnd != IntPtr.Zero)
     {
         HandleRef hwnd = new HandleRef(null, _hwnd);
         if (UnsafeNativeMethods.IsWindow(hwnd))
         {
             UnsafeNativeMethods.IntDestroyWindow(hwnd);
         }
         _hwnd = IntPtr.Zero;
     }
     if (_hBitmap != null && !_hBitmap.IsClosed)
     {
         UnsafeNativeMethods.DeleteObject(_hBitmap.MakeHandleRef(null).Handle);
         _hBitmap.Close();
         _hBitmap = null;
     }
     if (_wndClass != 0)
     {
         // Attempt to unregister the window class.  If the application has a second
         // splash screen which is still open this call will fail.  That's OK.
         if (UnsafeNativeMethods.IntUnregisterClass(new IntPtr(_wndClass), _hInstance) != 0)
         {
             _defWndProc = null; // Can safely release the wndproc delegate when there are no more splash screen instances
         }
         _wndClass = 0;
     }
     if (_resourceManager != null)
     {
         _resourceManager.ReleaseAllResources();
     }
 }
Ejemplo n.º 21
0
        private IntPtr CreateWindow(NativeMethods.BitmapHandle hBitmap, int width, int height, bool topMost)
        {
            if (_defWndProc == null)
            {
                _defWndProc = new MS.Win32.NativeMethods.WndProc(UnsafeNativeMethods.DefWindowProc);
            }

            MS.Win32.NativeMethods.WNDCLASSEX_D wndClass = new MS.Win32.NativeMethods.WNDCLASSEX_D();
            wndClass.cbSize = Marshal.SizeOf(typeof(MS.Win32.NativeMethods.WNDCLASSEX_D));
            wndClass.style = 3; /* CS_HREDRAW | CS_VREDRAW */
            wndClass.lpfnWndProc = null;
            wndClass.hInstance = _hInstance;
            wndClass.hCursor = IntPtr.Zero;
            wndClass.lpszClassName = CLASSNAME;
            wndClass.lpszMenuName = string.Empty;
            wndClass.lpfnWndProc = _defWndProc;

            // We chose to ignore re-registration errors in RegisterClassEx on the off chance that the user
            // wants to open multiple splash screens.
            _wndClass = MS.Win32.UnsafeNativeMethods.IntRegisterClassEx(wndClass);
            if (_wndClass == 0)
            {
                if (Marshal.GetLastWin32Error() != 0x582) /* class already registered */
                    throw new Win32Exception();
            }

            int screenWidth = MS.Win32.UnsafeNativeMethods.GetSystemMetrics(SM.CXSCREEN);
            int screenHeight = MS.Win32.UnsafeNativeMethods.GetSystemMetrics(SM.CYSCREEN);
            int x = (screenWidth - width) / 2;
            int y = (screenHeight - height) / 2;

            HandleRef nullHandle = new HandleRef(null, IntPtr.Zero);
            int windowCreateFlags =
                (int) NativeMethods.WS_EX_WINDOWEDGE |
                      NativeMethods.WS_EX_TOOLWINDOW |
                      NativeMethods.WS_EX_LAYERED |
                      (topMost ? NativeMethods.WS_EX_TOPMOST : 0);

            // CreateWindowEx will either succeed or throw
            IntPtr hWnd =  MS.Win32.UnsafeNativeMethods.CreateWindowEx(
                windowCreateFlags,
                CLASSNAME, SR.Get(SRID.SplashScreenIsLoading),
                MS.Win32.NativeMethods.WS_POPUP | MS.Win32.NativeMethods.WS_VISIBLE,
                x, y, width, height,
                nullHandle, nullHandle, new HandleRef(null, _hInstance), IntPtr.Zero);

            // Display the image on the window
            IntPtr hScreenDC = UnsafeNativeMethods.GetDC(new HandleRef());
            IntPtr memDC = UnsafeNativeMethods.CreateCompatibleDC(new HandleRef(null, hScreenDC));
            IntPtr hOldBitmap = UnsafeNativeMethods.SelectObject(new HandleRef(null, memDC), hBitmap.MakeHandleRef(null).Handle);

            NativeMethods.POINT newSize = new NativeMethods.POINT(width, height);
            NativeMethods.POINT newLocation = new NativeMethods.POINT(x, y);
            NativeMethods.POINT sourceLocation = new NativeMethods.POINT(0, 0);
            _blendFunc = new NativeMethods.BLENDFUNCTION();
            _blendFunc.BlendOp = NativeMethods.AC_SRC_OVER;
            _blendFunc.BlendFlags = 0;
            _blendFunc.SourceConstantAlpha = 255;
            _blendFunc.AlphaFormat = 1; /*AC_SRC_ALPHA*/

            bool result = UnsafeNativeMethods.UpdateLayeredWindow(hWnd, hScreenDC, newLocation, newSize,
                memDC, sourceLocation, 0, ref _blendFunc, NativeMethods.ULW_ALPHA);

            UnsafeNativeMethods.SelectObject(new HandleRef(null, memDC), hOldBitmap);
            UnsafeNativeMethods.ReleaseDC(new HandleRef(), new HandleRef(null, memDC));
            UnsafeNativeMethods.ReleaseDC(new HandleRef(), new HandleRef(null, hScreenDC));

            if (result == false)
            {
                UnsafeNativeMethods.HRESULT.Check(Marshal.GetHRForLastWin32Error());
            }

            return hWnd;
        }
Ejemplo n.º 22
0
 private void DestroyResources()
 {
     if (_dt != null)
     {
         _dt.Stop();
         _dt = null;
     }
     if (_hwnd != IntPtr.Zero)
     {
         HandleRef hwnd = new HandleRef(null, _hwnd);
         if (UnsafeNativeMethods.IsWindow(hwnd))
         {
             UnsafeNativeMethods.IntDestroyWindow(hwnd);
         }
         _hwnd = IntPtr.Zero;
     }
     if (_hBitmap != null && !_hBitmap.IsClosed)
     {
         UnsafeNativeMethods.DeleteObject(_hBitmap.MakeHandleRef(null).Handle);
         _hBitmap.Close();
         _hBitmap = null;
     }
     if (_wndClass != 0)
     {
         // Attempt to unregister the window class.  If the application has a second
         // splash screen which is still open this call will fail.  That's OK.
         if (UnsafeNativeMethods.IntUnregisterClass(new IntPtr(_wndClass), _hInstance) != 0)
         {
             _defWndProc = null; // Can safely release the wndproc delegate when there are no more splash screen instances
         }
         _wndClass = 0;
     }
     if (_resourceManager != null)
     {
         _resourceManager.ReleaseAllResources();
     }
 }
Ejemplo n.º 23
0
        /// <include file='doc\PageSetupDialog.uex' path='docs/doc[@for="PageSetupDialog.RunDialog"]/*' />
        /// <devdoc>
        /// </devdoc>
        /// <internalonly/>
        protected override bool RunDialog(IntPtr hwndOwner) {
            IntSecurity.SafePrinting.Demand();

            NativeMethods.WndProc hookProcPtr = new NativeMethods.WndProc(this.HookProc);
            if (pageSettings == null)
                throw new ArgumentException(SR.GetString(SR.PSDcantShowWithoutPage));

            NativeMethods.PAGESETUPDLG data = new NativeMethods.PAGESETUPDLG();
            data.lStructSize = Marshal.SizeOf(data);
            data.Flags = GetFlags();
            data.hwndOwner = hwndOwner;
            data.lpfnPageSetupHook = hookProcPtr;
            
            PrinterUnit toUnit = PrinterUnit.ThousandthsOfAnInch;

            // Refer VSWhidbey: 331160. Below was a breaking change from RTM and EVERETT even though this was a correct FIX.
            // EnableMetric is a new Whidbey property which we allow the users to choose between the AutoConversion or not.
            if (EnableMetric)
            {
                //take the Units of Measurement while determining the PrinterUnits...
                //bug (121347)...
                StringBuilder sb = new StringBuilder(2);
                int result = UnsafeNativeMethods.GetLocaleInfo(NativeMethods.LOCALE_USER_DEFAULT,NativeMethods.LOCALE_IMEASURE, sb,sb.Capacity);
                
                if (result > 0 && Int32.Parse(sb.ToString(), CultureInfo.InvariantCulture) == 0) {
                    toUnit = PrinterUnit.HundredthsOfAMillimeter;
                }
            }

            if (MinMargins != null) {
                Margins margins = PrinterUnitConvert.Convert(MinMargins, PrinterUnit.Display, toUnit);
                data.minMarginLeft = margins.Left;
                data.minMarginTop = margins.Top;
                data.minMarginRight = margins.Right;
                data.minMarginBottom = margins.Bottom;
            }

            if (pageSettings.Margins != null) {
                Margins margins = PrinterUnitConvert.Convert(pageSettings.Margins, PrinterUnit.Display, toUnit);
                data.marginLeft = margins.Left;
                data.marginTop = margins.Top;
                data.marginRight = margins.Right;
                data.marginBottom = margins.Bottom;
            }

            // Ensure that the margins are >= minMargins.
            // This is a requirement of the PAGESETUPDLG structure.
            //
            data.marginLeft = Math.Max(data.marginLeft, data.minMarginLeft);
            data.marginTop = Math.Max(data.marginTop, data.minMarginTop);
            data.marginRight = Math.Max(data.marginRight, data.minMarginRight);
            data.marginBottom = Math.Max(data.marginBottom, data.minMarginBottom);           

            PrinterSettings printer = (printerSettings == null) ? pageSettings.PrinterSettings : printerSettings;

            // GetHDevmode demands AllPrintingAndUnmanagedCode Permission : Since we are calling that function we should Assert the permision,
            IntSecurity.AllPrintingAndUnmanagedCode.Assert();
            try {
                data.hDevMode = printer.GetHdevmode(pageSettings);
                data.hDevNames = printer.GetHdevnames();
            }
            finally {
                CodeAccessPermission.RevertAssert();
            }

            try {
                bool status = UnsafeNativeMethods.PageSetupDlg(data);
                if (!status) {
                    // Debug.WriteLine(Windows.CommonDialogErrorToString(Windows.CommDlgExtendedError()));
                    return false;
                }
                
                UpdateSettings(data, pageSettings, printerSettings); // yes, printerSettings, not printer
                return true;
            }
            finally {
                UnsafeNativeMethods.GlobalFree(new HandleRef(data, data.hDevMode));
                UnsafeNativeMethods.GlobalFree(new HandleRef(data, data.hDevNames));
            }
        }
Ejemplo n.º 24
0
        // This method should only be called from Dispose. Otherwise assumptions about the disposing/finalize state could be violated.
        // force - when true, remove this subclass from the WndProc chain regardless of
        //          its current position.  When false, remove this subclass only
        //          if it is possible to do so without damaging other WndProcs
        //          (i.e. only if this is at the head of the chain).
        //
        // Removing this subclass from the WndProc chain when it is not at the head
        // also removes all other WndProcs that appear before this one on the chain,
        // so is generally not appropriate. It is OK in the following situations:
        //  a) in response to the WM_NCDESTROY message
        //  b) in response to the AppDomainProcessExit event
        //  c) in response to the AppDomainExit event
        // In cases (a) and (b) the HWND is being destroyed, so the earlier
        // WndProcs are no longer useful anyway.  In case (c), we have to remove
        // all managed code from the chain lest it be called after it has been
        // removed from memory;  removing earlier WndProcs is unfortunate, but
        // necessary.  [Note that at AppDomainExit we remove all managed WndProcs,
        // regardless of which AppDomain they came from.  There is room for
        // improvement here - we could remove only the ones belong to the AppDomain
        // that is exiting.  This situation seems too unlikely to worry about in V1.]
        //
        // This method returns true if the subclass is no longer in the WndProc chain.
        //
        private bool UnhookWindowProc(bool force)
        {
            // if we're not in the WndProc chain, there's nothing to do
            if (_bond == Bond.Unattached || _bond == Bond.Detached)
            {
                return(true);
            }

            // we'll remove ourselves from the chain if we're at the head, or if
            // the 'force' parameter was true.
            if (!force)
            {
                NativeMethods.WndProc currentWndProc = UnsafeNativeMethods.GetWindowLongWndProc(new HandleRef(this, _hwndAttached));
                force = (currentWndProc == _attachedWndProc);
            }

            // if we're not unhooking, return and report
            if (!force)
            {
                return(false);
            }

            // unhook from the tracker
            _bond = Bond.Orphaned;  // ignore messages while we're unhooking
            ManagedWndProcTracker.UnhookHwndSubclass(this);

            // unhook, the Win32 way
            try
            {
                UnsafeNativeMethods.CriticalSetWindowLong(_hwndHandleRef, NativeMethods.GWL_WNDPROC, _oldWndProc);
            }
            catch (System.ComponentModel.Win32Exception e)
            {
                if (e.NativeErrorCode != 1400) // ERROR_INVALID_WINDOW_HANDLE
                {
                    throw;
                }
            }


            // clear our state
            _bond = Bond.Detached;

            _oldWndProc      = IntPtr.Zero;
            _attachedWndProc = null;
            _hwndAttached    = IntPtr.Zero;
            _hwndHandleRef   = new HandleRef(null, IntPtr.Zero);

            // un-Pin this object.
            // Note: the GC is free to collect this object at anytime
            // after we have freed this handle - that is, once all
            // other managed references go away.

            //AvDebug.Assert(_gcHandle.IsAllocated, "External GC handle has not been allocated.");

            if (null != _gcHandle)
            {
                _gcHandle.Free();
            }

            return(true);
        }
Ejemplo n.º 25
0
 private bool RunDialogOld(IntPtr hWndOwner)
 {
     NativeMethods.WndProc hookProcPtr = new NativeMethods.WndProc(this.HookProc);
     NativeMethods.OPENFILENAME_I ofn = new NativeMethods.OPENFILENAME_I();
     try {
         charBuffer = CharBuffer.CreateBuffer(FILEBUFSIZE);
         if (fileNames != null) {
             charBuffer.PutString(fileNames[0]);
         }
         ofn.lStructSize = Marshal.SizeOf(typeof(NativeMethods.OPENFILENAME_I));
         // Degrade to the older style dialog if we're not on Win2K.
         // We do this by setting the struct size to a different value
         //
         if (Environment.OSVersion.Platform != System.PlatformID.Win32NT ||
             Environment.OSVersion.Version.Major < 5) {
             ofn.lStructSize = 0x4C;
         }
         ofn.hwndOwner = hWndOwner;
         ofn.hInstance = Instance;
         ofn.lpstrFilter = MakeFilterString(filter, this.DereferenceLinks);
         ofn.nFilterIndex = filterIndex;
         ofn.lpstrFile = charBuffer.AllocCoTaskMem();
         ofn.nMaxFile = FILEBUFSIZE;
         ofn.lpstrInitialDir = initialDir;
         ofn.lpstrTitle = title;
         ofn.Flags = Options | (NativeMethods.OFN_EXPLORER | NativeMethods.OFN_ENABLEHOOK | NativeMethods.OFN_ENABLESIZING);
         ofn.lpfnHook = hookProcPtr;
         ofn.FlagsEx = NativeMethods.OFN_USESHELLITEM;
         if (defaultExt != null && AddExtension) {
             ofn.lpstrDefExt = defaultExt;
         }
         //Security checks happen here
         return RunFileDialog(ofn);
     }
     finally {
         charBuffer = null;
         if (ofn.lpstrFile != IntPtr.Zero) {
             Marshal.FreeCoTaskMem(ofn.lpstrFile);
         }
     }
 }
Ejemplo n.º 26
0
        public DialogResult ShowDialog( IWin32Window owner ) {

            IntSecurity.SafeSubWindows.Demand();

            if (!SystemInformation.UserInteractive) {
                throw new InvalidOperationException(SR.GetString(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;
        }
Ejemplo n.º 27
0
        /// <include file='doc\FontDialog.uex' path='docs/doc[@for="FontDialog.RunDialog"]/*' />
        /// <internalonly/>
        /// <devdoc>
        ///    <para>
        ///       The actual implementation of running the dialog. Inheriting classes
        ///       should override this if they want to add more functionality, and call
        ///       base.runDialog() if necessary
        ///       
        ///    </para>
        /// </devdoc>
        protected override bool RunDialog(IntPtr hWndOwner) {
            NativeMethods.WndProc hookProcPtr = new NativeMethods.WndProc(this.HookProc);
            NativeMethods.CHOOSEFONT cf = new NativeMethods.CHOOSEFONT();
            IntPtr screenDC = UnsafeNativeMethods.GetDC(NativeMethods.NullHandleRef);
            NativeMethods.LOGFONT lf = new NativeMethods.LOGFONT();

            Graphics graphics = Graphics.FromHdcInternal(screenDC);

            // SECREVIEW : The Font.ToLogFont method is marked with the 'unsafe' modifier cause it needs to write bytes into the logFont struct,
            //             here we are passing that struct so the assert is safe.
            //
            IntSecurity.ObjectFromWin32Handle.Assert();
            try {
                Font.ToLogFont(lf, graphics);
            }
            finally {
                CodeAccessPermission.RevertAssert();
                graphics.Dispose();
            }
            UnsafeNativeMethods.ReleaseDC(NativeMethods.NullHandleRef, new HandleRef(null, screenDC));

            IntPtr logFontPtr = IntPtr.Zero;
            try {
                logFontPtr = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(NativeMethods.LOGFONT)));
                Marshal.StructureToPtr(lf, logFontPtr, false);

                cf.lStructSize = Marshal.SizeOf(typeof(NativeMethods.CHOOSEFONT));
                cf.hwndOwner = hWndOwner;
                cf.hDC = IntPtr.Zero;
                cf.lpLogFont = logFontPtr;
                cf.Flags = Options | NativeMethods.CF_INITTOLOGFONTSTRUCT | NativeMethods.CF_ENABLEHOOK;
                if (minSize > 0 || maxSize > 0) {
                    cf.Flags |= NativeMethods.CF_LIMITSIZE;
                }

                //if ShowColor=true then try to draw the sample text in color,
                //if ShowEffects=false then we will draw the sample text in standard control text color regardless.
                //(limitation of windows control)
                //
                if (ShowColor || ShowEffects) {
                    cf.rgbColors = ColorTranslator.ToWin32(color);
                }
                else {
                    cf.rgbColors = ColorTranslator.ToWin32(SystemColors.ControlText);
                }

                cf.lpfnHook = hookProcPtr;
                cf.hInstance = UnsafeNativeMethods.GetModuleHandle(null);
                cf.nSizeMin = minSize;
                if (maxSize == 0) {
                    cf.nSizeMax = Int32.MaxValue;
                }
                else {
                    cf.nSizeMax = maxSize;
                }
                Debug.Assert(cf.nSizeMin <= cf.nSizeMax, "min and max font sizes are the wrong way around");
                if (!SafeNativeMethods.ChooseFont(cf)) return false;


                NativeMethods.LOGFONT lfReturned = null;
                lfReturned = (NativeMethods.LOGFONT)UnsafeNativeMethods.PtrToStructure(logFontPtr, typeof(NativeMethods.LOGFONT));

                if (lfReturned.lfFaceName != null && lfReturned.lfFaceName.Length > 0) {
                    lf = lfReturned;
                    UpdateFont(lf);
                    UpdateColor(cf.rgbColors);
                }

                return true;
            }
            finally {
                if (logFontPtr != IntPtr.Zero)
                    Marshal.FreeCoTaskMem(logFontPtr);
            }
        }
Ejemplo n.º 28
0
        private bool RunLegacyDialog(IntPtr hwndOwner)
        {
            // Once we run the dialog, all of our communication with it is handled
            // by processing WM_NOTIFY messages in our hook procedure, this.HookProc.
            // NativeMethods.WndProc is a delegate with the appropriate signature
            // needed for a Win32 window hook procedure.
            NativeMethods.WndProc hookProcPtr = new NativeMethods.WndProc(this.HookProc);

            // Create a new OPENFILENAME structure.  OPENFILENAME is a structure defined
            // in Win32's commdlg.h that contains most of the information needed to
            // successfully display a file dialog box.
            // NOTE:  Despite the name, OPENFILENAME is the proper structure for both
            //        file open and file save dialogs.
            NativeMethods.OPENFILENAME_I ofn = new NativeMethods.OPENFILENAME_I();

            // do everything in a try block, so we always free memory in the finalizer
            try
            {
                // Create an appropriately sized buffer to hold the filenames.
                // The buffer's initial size is controlled by the FILEBUFSIZE constant,
                // an arbitrary value chosen so that we will rarely have to grow the buffer.
                _charBuffer = CharBuffer.CreateBuffer(FILEBUFSIZE);

                // If we have a filename stored in our internal array _fileNames,
                // place it in the buffer as a default filename.
                if (_fileNames != null)
                {
                    _charBuffer.PutString(_fileNames[0]);
                }

                // --- Set up the OPENFILENAME structure ---

                // lStructSize
                // Specifies the length, in bytes, of the structure. 
                ofn.lStructSize = Marshal.SizeOf(typeof(NativeMethods.OPENFILENAME_I));

                // hwndOwner
                // Handle to the window that owns the dialog box. This member can be any
                // valid window handle, or it can be NULL if the dialog box has no owner.
                ofn.hwndOwner = hwndOwner;

                // hInstance
                // This property is ignored unless OFN_ENABLETEMPLATEHANDLE or 
                // OFN_ENABLETEMPLATE are set.  Since we do not set either,
                // hInstance is ignored, so we can set it to zero.
                ofn.hInstance = IntPtr.Zero;

                // lpstrFilter
                // Pointer to a buffer containing pairs of null-terminated filter strings. 
                // The last string in the buffer must be terminated by two NULL characters. 
                // Since our filter strings are stored terminated by vertical bar '|' chars,
                // we call MakeFilterString to reformat and validate the filter string.
                ofn.lpstrFilter = MakeFilterString(_filter, this.DereferenceLinks);

                // nFilterIndex
                // Specifies the index of the currently selected filter in the File Types 
                // control.  Note that since 0 is reserved for a custom filter (which we
                // do not support), our valid filter indexes begin at 1.
                ofn.nFilterIndex = _filterIndex;

                // lpstrFile
                // Pointer to a buffer used to store filenames.  When initializing the
                // dialog, this name is used as an initial value in the File Name edit
                // control.  When files are selected and the function returns, the buffer
                // contains the full path to every file selected.
                ofn.lpstrFile = _charBuffer.AllocCoTaskMem();

                // nMaxFile
                // Size of the lpstrFile buffer in number of Unicode characters.
                ofn.nMaxFile = _charBuffer.Length;

                // lpstrInitialDir
                // Pointer to a null terminated string that can specify the initial directory.
                // A relatively complex algorithm is used to determine which directory is
                // actually used as the initial directory - for details, see MSDN for the
                // OPENFILENAME structure.
                ofn.lpstrInitialDir = _initialDirectory.Value;

                // lpstrTitle
                // Pointer to a string to be placed in the title bar of the dialog box.
                // NULL causes the title bar to display the operating system default string.
                ofn.lpstrTitle = _title.Value;

                // Flags
                // A set of bit flags you can use to initialize the dialog box.
                // Most of these will be set through public properties that then call
                // GetOption or SetOption.  We retrieve the flags using the Options property
                // and then add three additional flags here:
                //
                //     OFN_EXPLORER
                //         display an Explorer-style box (newer style)
                //     OFN_ENABLEHOOK
                //         enable the hook procedure (important for much of our functionality)
                //     OFN_ENABLESIZING
                //         allow the user to resize the dialog box
                //         
                ofn.Flags = Options | (NativeMethods.OFN_EXPLORER |
                                       NativeMethods.OFN_ENABLEHOOK |
                                       NativeMethods.OFN_ENABLESIZING);

                // lpfnHook
                // Pointer to the hook procedure.
                // Ignored unless OFN_ENABLEHOOK is set in Flags.
                ofn.lpfnHook = hookProcPtr;

                // FlagsEx
                // Can be either zero or OFN_EX_NOPLACESBAR, depending on whether
                // the Places Bar (My Computer/Favorites/etc) should be shown on the
                // left side of the file dialog.
                ofn.FlagsEx = NativeMethods.OFN_USESHELLITEM;

                // lpstrDefExt
                // Pointer to a buffer that contains the default extension;  it will
                // be appended to filenames if the user does not type an extension.
                // Only the first three characters are appended by Windows.  If this
                // is NULL, no extension is appended.
                if (_defaultExtension != null && AddExtension)
                {
                    ofn.lpstrDefExt = _defaultExtension;
                }

                // Call into either OpenFileDialog or SaveFileDialog to show the
                // actual dialog box.  This call blocks until the dialog is closed;
                // while dialog is open, all interaction is through HookProc.
                return RunFileDialog(ofn);
            }
            finally
            {
                // Explicitly set the character buffer to null.
                _charBuffer = null;

                // If there is still a pointer to a memory location in
                // ofn.lpstrFile, we explicitly free that memory here.
                if (ofn.lpstrFile != IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(ofn.lpstrFile);
                }
            }
        }
Ejemplo n.º 29
0
        private IntPtr CreateWindow(NativeMethods.BitmapHandle hBitmap, int width, int height, bool topMost)
        {
            if (_defWndProc == null)
            {
                _defWndProc = new MS.Win32.NativeMethods.WndProc(UnsafeNativeMethods.DefWindowProc);
            }

            MS.Win32.NativeMethods.WNDCLASSEX_D wndClass = new MS.Win32.NativeMethods.WNDCLASSEX_D();
            wndClass.cbSize        = Marshal.SizeOf(typeof(MS.Win32.NativeMethods.WNDCLASSEX_D));
            wndClass.style         = 3; /* CS_HREDRAW | CS_VREDRAW */
            wndClass.lpfnWndProc   = null;
            wndClass.hInstance     = _hInstance;
            wndClass.hCursor       = IntPtr.Zero;
            wndClass.lpszClassName = CLASSNAME;
            wndClass.lpszMenuName  = string.Empty;
            wndClass.lpfnWndProc   = _defWndProc;

            // We chose to ignore re-registration errors in RegisterClassEx on the off chance that the user
            // wants to open multiple splash screens.
            _wndClass = MS.Win32.UnsafeNativeMethods.IntRegisterClassEx(wndClass);
            if (_wndClass == 0)
            {
                if (Marshal.GetLastWin32Error() != 0x582) /* class already registered */
                {
                    throw new Win32Exception();
                }
            }

            int screenWidth  = MS.Win32.UnsafeNativeMethods.GetSystemMetrics(SM.CXSCREEN);
            int screenHeight = MS.Win32.UnsafeNativeMethods.GetSystemMetrics(SM.CYSCREEN);
            int x            = (screenWidth - width) / 2;
            int y            = (screenHeight - height) / 2;

            HandleRef nullHandle        = new HandleRef(null, IntPtr.Zero);
            int       windowCreateFlags =
                (int)NativeMethods.WS_EX_WINDOWEDGE |
                NativeMethods.WS_EX_TOOLWINDOW |
                NativeMethods.WS_EX_LAYERED |
                (topMost ? NativeMethods.WS_EX_TOPMOST : 0);

            // CreateWindowEx will either succeed or throw
            IntPtr hWnd = MS.Win32.UnsafeNativeMethods.CreateWindowEx(
                windowCreateFlags,
                CLASSNAME, SR.Get(SRID.SplashScreenIsLoading),
                MS.Win32.NativeMethods.WS_POPUP | MS.Win32.NativeMethods.WS_VISIBLE,
                x, y, width, height,
                nullHandle, nullHandle, new HandleRef(null, _hInstance), IntPtr.Zero);

            // Display the image on the window
            IntPtr hScreenDC  = UnsafeNativeMethods.GetDC(new HandleRef());
            IntPtr memDC      = UnsafeNativeMethods.CreateCompatibleDC(new HandleRef(null, hScreenDC));
            IntPtr hOldBitmap = UnsafeNativeMethods.SelectObject(new HandleRef(null, memDC), hBitmap.MakeHandleRef(null).Handle);

            NativeMethods.POINT newSize        = new NativeMethods.POINT(width, height);
            NativeMethods.POINT newLocation    = new NativeMethods.POINT(x, y);
            NativeMethods.POINT sourceLocation = new NativeMethods.POINT(0, 0);
            _blendFunc                     = new NativeMethods.BLENDFUNCTION();
            _blendFunc.BlendOp             = NativeMethods.AC_SRC_OVER;
            _blendFunc.BlendFlags          = 0;
            _blendFunc.SourceConstantAlpha = 255;
            _blendFunc.AlphaFormat         = 1; /*AC_SRC_ALPHA*/

            bool result = UnsafeNativeMethods.UpdateLayeredWindow(hWnd, hScreenDC, newLocation, newSize,
                                                                  memDC, sourceLocation, 0, ref _blendFunc, NativeMethods.ULW_ALPHA);

            UnsafeNativeMethods.SelectObject(new HandleRef(null, memDC), hOldBitmap);
            UnsafeNativeMethods.ReleaseDC(new HandleRef(), new HandleRef(null, memDC));
            UnsafeNativeMethods.ReleaseDC(new HandleRef(), new HandleRef(null, hScreenDC));

            if (result == false)
            {
                UnsafeNativeMethods.HRESULT.Check(Marshal.GetHRForLastWin32Error());
            }

            return(hWnd);
        }
Ejemplo n.º 30
0
        protected override bool RunDialog(IntPtr hwndOwner)
        {
            NativeMethods.WndProc hookProcPtr = new NativeMethods.WndProc(HookProc);
            if (pageSettings == null)
            {
                throw new ArgumentException(SR.PSDcantShowWithoutPage);
            }

            NativeMethods.PAGESETUPDLG data = new NativeMethods.PAGESETUPDLG();
            data.lStructSize       = Marshal.SizeOf(data);
            data.Flags             = GetFlags();
            data.hwndOwner         = hwndOwner;
            data.lpfnPageSetupHook = hookProcPtr;

            PrinterUnit toUnit = PrinterUnit.ThousandthsOfAnInch;

            // Below was a breaking change from RTM and EVERETT even though this was a correct FIX.
            // EnableMetric is a new Whidbey property which we allow the users to choose between the AutoConversion or not.
            if (EnableMetric)
            {
                //take the Units of Measurement while determining the PrinterUnits...
                //
                StringBuilder sb     = new StringBuilder(2);
                int           result = UnsafeNativeMethods.GetLocaleInfo(NativeMethods.LOCALE_USER_DEFAULT, NativeMethods.LOCALE_IMEASURE, sb, sb.Capacity);

                if (result > 0 && int.Parse(sb.ToString(), CultureInfo.InvariantCulture) == 0)
                {
                    toUnit = PrinterUnit.HundredthsOfAMillimeter;
                }
            }

            if (MinMargins != null)
            {
                Margins margins = PrinterUnitConvert.Convert(MinMargins, PrinterUnit.Display, toUnit);
                data.minMarginLeft   = margins.Left;
                data.minMarginTop    = margins.Top;
                data.minMarginRight  = margins.Right;
                data.minMarginBottom = margins.Bottom;
            }

            if (pageSettings.Margins != null)
            {
                Margins margins = PrinterUnitConvert.Convert(pageSettings.Margins, PrinterUnit.Display, toUnit);
                data.marginLeft   = margins.Left;
                data.marginTop    = margins.Top;
                data.marginRight  = margins.Right;
                data.marginBottom = margins.Bottom;
            }

            // Ensure that the margins are >= minMargins.
            // This is a requirement of the PAGESETUPDLG structure.
            //
            data.marginLeft   = Math.Max(data.marginLeft, data.minMarginLeft);
            data.marginTop    = Math.Max(data.marginTop, data.minMarginTop);
            data.marginRight  = Math.Max(data.marginRight, data.minMarginRight);
            data.marginBottom = Math.Max(data.marginBottom, data.minMarginBottom);

            PrinterSettings printer = printerSettings ?? pageSettings.PrinterSettings;

            data.hDevMode  = printer.GetHdevmode(pageSettings);
            data.hDevNames = printer.GetHdevnames();

            try
            {
                bool status = UnsafeNativeMethods.PageSetupDlg(data);
                if (!status)
                {
                    // Debug.WriteLine(Windows.CommonDialogErrorToString(Windows.CommDlgExtendedError()));
                    return(false);
                }

                UpdateSettings(data, pageSettings, printerSettings); // yes, printerSettings, not printer
                return(true);
            }
            finally
            {
                UnsafeNativeMethods.GlobalFree(new HandleRef(data, data.hDevMode));
                UnsafeNativeMethods.GlobalFree(new HandleRef(data, data.hDevNames));
            }
        }
Ejemplo n.º 31
0
        private IntPtr CreateBroadcastWindow() {

            // Register the window class.
            //
            NativeMethods.WNDCLASS_I wndclassi = new NativeMethods.WNDCLASS_I();
            IntPtr hInstance = UnsafeNativeMethods.GetModuleHandle(null);

            if (!UnsafeNativeMethods.GetClassInfo(new HandleRef(this, hInstance), WndClass.lpszClassName, wndclassi)) {

                if (UnsafeNativeMethods.RegisterClass(WndClass) == 0) {
                    windowProc = null;
                    Debug.Fail("Unable to register broadcast window class");
                    return IntPtr.Zero;
                }
            }
            else {
                //lets double check the wndproc returned by getclassinfo for defwndproc.
                if (wndclassi.lpfnWndProc == DefWndProc) {

                    //if we are in there, it means className belongs to an unloaded appdomain.
                    short atom = 0;

                    //try to unregister it.
                    if (0 != UnsafeNativeMethods.UnregisterClass(WndClass.lpszClassName, new HandleRef(null, UnsafeNativeMethods.GetModuleHandle(null)))) {
                        atom = UnsafeNativeMethods.RegisterClass(WndClass);
                    }

                    if (atom == 0) {
                        do {
                            BumpQualifier();
                            atom = UnsafeNativeMethods.RegisterClass(WndClass);
                        } while (atom == 0 && Marshal.GetLastWin32Error() == NativeMethods.ERROR_CLASS_ALREADY_EXISTS);
                    }
                }
            }

            // And create an instance of the window.
            //
            IntPtr hwnd = UnsafeNativeMethods.CreateWindowEx(
                                                            0,
                                                            WndClass.lpszClassName,
                                                            WndClass.lpszClassName,
                                                            NativeMethods.WS_POPUP,
                                                            0, 0, 0, 0, NativeMethods.NullHandleRef, NativeMethods.NullHandleRef,
                                                            new HandleRef(this, hInstance), null);
            return hwnd;
        }
Ejemplo n.º 32
0
        public HwndWrapper(
            int classStyle,
            int style,
            int exStyle,
            int x,
            int y,
            int width,
            int height,
            string name,
            IntPtr parent,
            HwndWrapperHook[] hooks)
        {
            _ownerThreadID = new SecurityCriticalDataForSet <int>(Thread.CurrentThread.ManagedThreadId);


            // First, add the set of hooks.  This allows the hooks to receive the
            // messages sent to the window very early in the process.
            if (hooks != null)
            {
                for (int i = 0, iEnd = hooks.Length; i < iEnd; i++)
                {
                    if (null != hooks[i])
                    {
                        AddHook(hooks[i]);
                    }
                }
            }


            _wndProc = new SecurityCriticalData <HwndWrapperHook>(new HwndWrapperHook(WndProc));

            // We create the HwndSubclass object so that we can use its
            // window proc directly.  We will not be "subclassing" the
            // window we create.
            HwndSubclass hwndSubclass = new HwndSubclass(_wndProc.Value);

            // Register a unique window class for this instance.
            NativeMethods.WNDCLASSEX_D wc_d = new NativeMethods.WNDCLASSEX_D();

            IntPtr hNullBrush = UnsafeNativeMethods.CriticalGetStockObject(NativeMethods.NULL_BRUSH);

            if (hNullBrush == IntPtr.Zero)
            {
                throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
            }

            IntPtr hInstance = UnsafeNativeMethods.GetModuleHandle(null);

            // We need to keep the Delegate object alive through the call to CreateWindowEx().
            // Subclass.WndProc will install a better delegate (to the same function) when it
            // processes the first message.
            // But this first delegate needs be held alive until then.
            NativeMethods.WndProc initialWndProc = new NativeMethods.WndProc(hwndSubclass.SubclassWndProc);

            // The class name is a concat of AppName, ThreadName, and RandomNumber.
            // Register will fail if the string gets over 255 in length.
            // So limit each part to a reasonable amount.
            string appName;

            if (null != AppDomain.CurrentDomain.FriendlyName && 128 <= AppDomain.CurrentDomain.FriendlyName.Length)
            {
                appName = AppDomain.CurrentDomain.FriendlyName.Substring(0, 128);
            }
            else
            {
                appName = AppDomain.CurrentDomain.FriendlyName;
            }

            string threadName;

            if (null != Thread.CurrentThread.Name && 64 <= Thread.CurrentThread.Name.Length)
            {
                threadName = Thread.CurrentThread.Name.Substring(0, 64);
            }
            else
            {
                threadName = Thread.CurrentThread.Name;
            }

            // Create a suitable unique class name.
            _classAtom = 0;
            string randomName = Guid.NewGuid().ToString();
            string className  = String.Format(CultureInfo.InvariantCulture, "HwndWrapper[{0};{1};{2}]", appName, threadName, randomName);

            wc_d.cbSize        = Marshal.SizeOf(typeof(NativeMethods.WNDCLASSEX_D));
            wc_d.style         = classStyle;
            wc_d.lpfnWndProc   = initialWndProc;
            wc_d.cbClsExtra    = 0;
            wc_d.cbWndExtra    = 0;
            wc_d.hInstance     = hInstance;
            wc_d.hIcon         = IntPtr.Zero;
            wc_d.hCursor       = IntPtr.Zero;
            wc_d.hbrBackground = hNullBrush;
            wc_d.lpszMenuName  = "";
            wc_d.lpszClassName = className;
            wc_d.hIconSm       = IntPtr.Zero;

            // Register the unique class for this instance.
            // Note we use a GUID in the name so we are confident that
            // the class name should be unique.  And RegisterClassEx won't
            // fail (for that reason).
            _classAtom = UnsafeNativeMethods.RegisterClassEx(wc_d);

            // call CreateWindow
            _isInCreateWindow = true;
            try {
                _handle = new SecurityCriticalDataClass <IntPtr>(UnsafeNativeMethods.CreateWindowEx(exStyle,
                                                                                                    className,
                                                                                                    name,
                                                                                                    style,
                                                                                                    x,
                                                                                                    y,
                                                                                                    width,
                                                                                                    height,
                                                                                                    new HandleRef(null, parent),
                                                                                                    new HandleRef(null, IntPtr.Zero),
                                                                                                    new HandleRef(null, IntPtr.Zero),
                                                                                                    null));
            }
            finally
            {
                _isInCreateWindow = false;
                if (_handle == null || _handle.Value == IntPtr.Zero)
                {
                    // Because the HwndSubclass is pinned, but the HWND creation failed,
                    // we need to manually clean it up.
                    hwndSubclass.Dispose();
                }
            }
            GC.KeepAlive(initialWndProc);
        }
Ejemplo n.º 33
0
        // VSWhidbey 93449: Due to the nature of PRINTDLGEX vs PRINTDLG, separate but similar methods
        // are required for showing the print dialog on Win2k and newer OS'.
        private bool ShowPrintDialog(IntPtr hwndOwner, NativeMethods.WndProc hookProcPtr, NativeMethods.PRINTDLG data)
        {
            data.Flags         = GetFlags();
            data.nCopies       = (short)PrinterSettings.Copies;
            data.hwndOwner     = hwndOwner;
            data.lpfnPrintHook = hookProcPtr;

            IntSecurity.AllPrintingAndUnmanagedCode.Assert();

            try {
                if (PageSettings == null)
                {
                    data.hDevMode = PrinterSettings.GetHdevmode();
                }
                else
                {
                    data.hDevMode = PrinterSettings.GetHdevmode(PageSettings);
                }

                data.hDevNames = PrinterSettings.GetHdevnames();
            }
            catch (InvalidPrinterException) {
                data.hDevMode  = IntPtr.Zero;
                data.hDevNames = IntPtr.Zero;
                // Leave those fields null; Windows will fill them in
            }
            finally {
                CodeAccessPermission.RevertAssert();
            }

            try {
                // Windows doesn't like it if page numbers are invalid
                if (AllowSomePages)
                {
                    if (PrinterSettings.FromPage < PrinterSettings.MinimumPage ||
                        PrinterSettings.FromPage > PrinterSettings.MaximumPage)
                    {
                        throw new ArgumentException(SR.GetString(SR.PDpageOutOfRange, "FromPage"));
                    }
                    if (PrinterSettings.ToPage < PrinterSettings.MinimumPage ||
                        PrinterSettings.ToPage > PrinterSettings.MaximumPage)
                    {
                        throw new ArgumentException(SR.GetString(SR.PDpageOutOfRange, "ToPage"));
                    }
                    if (PrinterSettings.ToPage < PrinterSettings.FromPage)
                    {
                        throw new ArgumentException(SR.GetString(SR.PDpageOutOfRange, "FromPage"));
                    }

                    data.nFromPage = (short)PrinterSettings.FromPage;
                    data.nToPage   = (short)PrinterSettings.ToPage;
                    data.nMinPage  = (short)PrinterSettings.MinimumPage;
                    data.nMaxPage  = (short)PrinterSettings.MaximumPage;
                }

                if (!UnsafeNativeMethods.PrintDlg(data))
                {
                    return(false);
                }

                IntSecurity.AllPrintingAndUnmanagedCode.Assert();
                try {
                    UpdatePrinterSettings(data.hDevMode, data.hDevNames, data.nCopies, data.Flags, settings, PageSettings);
                }
                finally {
                    CodeAccessPermission.RevertAssert();
                }
                PrintToFile = ((data.Flags & NativeMethods.PD_PRINTTOFILE) != 0);
                PrinterSettings.PrintToFile = PrintToFile;

                if (AllowSomePages)
                {
                    PrinterSettings.FromPage = data.nFromPage;
                    PrinterSettings.ToPage   = data.nToPage;
                }

                // Fix Dev10 #575399, when the flag PD_USEDEVMODECOPIESANDCOLLATE is not set,
                // PRINTDLG.nCopies or PRINTDLG.nCopies indicates the number of copies the user wants
                // to print, and the PD_COLLATE flag in the Flags member indicates
                // whether the user wants to print them collated.
                // Due to a Windows OS Bug 558734, we don't need to consider Windows XP and before
                if ((data.Flags & NativeMethods.PD_USEDEVMODECOPIESANDCOLLATE) == 0)
                {
                    if (Environment.OSVersion.Version.Major >= 6)
                    {
                        PrinterSettings.Copies  = data.nCopies;
                        PrinterSettings.Collate = ((data.Flags & NativeMethods.PD_COLLATE) == NativeMethods.PD_COLLATE);
                    }
                }

                return(true);
            }
            finally {
                UnsafeNativeMethods.GlobalFree(new HandleRef(data, data.hDevMode));
                UnsafeNativeMethods.GlobalFree(new HandleRef(data, data.hDevNames));
            }
        }
Ejemplo n.º 34
0
 public static extern IntPtr SetWindowLongPtr64(HandleRef hWnd, int nIndex, NativeMethods.WndProc wndproc);
Ejemplo n.º 35
0
        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);
        }
Ejemplo n.º 36
0
 public static extern IntPtr SetWindowLongPtrWndProc(HandleRef hWnd, int nIndex, NativeMethods.WndProc dwNewLong);
Ejemplo n.º 37
0
        /// <include file='doc\PageSetupDialog.uex' path='docs/doc[@for="PageSetupDialog.RunDialog"]/*' />
        /// <devdoc>
        /// </devdoc>
        /// <internalonly/>
        protected override bool RunDialog(IntPtr hwndOwner)
        {
            IntSecurity.SafePrinting.Demand();

            NativeMethods.WndProc hookProcPtr = new NativeMethods.WndProc(this.HookProc);
            if (pageSettings == null)
            {
                throw new ArgumentException(SR.GetString(SR.PSDcantShowWithoutPage));
            }

            NativeMethods.PAGESETUPDLG data = new NativeMethods.PAGESETUPDLG();
            data.lStructSize       = Marshal.SizeOf(data);
            data.Flags             = GetFlags();
            data.hwndOwner         = hwndOwner;
            data.lpfnPageSetupHook = hookProcPtr;

            if (MinMargins != null)
            {
                PrinterUnit toUnit  = PrinterUnit.ThousandthsOfAnInch;
                Margins     margins = PrinterUnitConvert.Convert(MinMargins, PrinterUnit.Display, toUnit);
                data.minMarginLeft   = margins.Left;
                data.minMarginTop    = margins.Top;
                data.minMarginRight  = margins.Right;
                data.minMarginBottom = margins.Bottom;
            }

            if (pageSettings.Margins != null)
            {
                PrinterUnit toUnit  = PrinterUnit.ThousandthsOfAnInch;
                Margins     margins = PrinterUnitConvert.Convert(pageSettings.Margins, PrinterUnit.Display, toUnit);
                data.marginLeft   = margins.Left;
                data.marginTop    = margins.Top;
                data.marginRight  = margins.Right;
                data.marginBottom = margins.Bottom;
            }

            // Ensure that the margins are >= minMargins.
            // This is a requirement of the PAGESETUPDLG structure.
            //
            data.marginLeft   = Math.Max(data.marginLeft, data.minMarginLeft);
            data.marginTop    = Math.Max(data.marginTop, data.minMarginTop);
            data.marginRight  = Math.Max(data.marginRight, data.minMarginRight);
            data.marginBottom = Math.Max(data.marginBottom, data.minMarginBottom);

            PrinterSettings printer = (printerSettings == null) ? pageSettings.PrinterSettings : printerSettings;

            IntSecurity.AllPrinting.Assert();

            try {
                data.hDevMode  = printer.GetHdevmode(pageSettings);
                data.hDevNames = printer.GetHdevnames();
            }
            finally {
                CodeAccessPermission.RevertAssert();
            }

            try {
                bool status = UnsafeNativeMethods.PageSetupDlg(data);
                if (!status)
                {
                    // Debug.WriteLine(Windows.CommonDialogErrorToString(Windows.CommDlgExtendedError()));
                    return(false);
                }

                UpdateSettings(data, pageSettings, printerSettings); // yes, printerSettings, not printer
                return(true);
            }
            finally {
                UnsafeNativeMethods.GlobalFree(new HandleRef(data, data.hDevMode));
                UnsafeNativeMethods.GlobalFree(new HandleRef(data, data.hDevNames));
            }
        }
Ejemplo n.º 38
0
        private bool ShowPrintDialog(IntPtr hwndOwner, NativeMethods.WndProc hookProcPtr, NativeMethods.PRINTDLG data)
        {
            data.Flags         = GetFlags();
            data.nCopies       = (short)PrinterSettings.Copies;
            data.hwndOwner     = hwndOwner;
            data.lpfnPrintHook = hookProcPtr;

            try
            {
                if (PageSettings == null)
                {
                    data.hDevMode = PrinterSettings.GetHdevmode();
                }
                else
                {
                    data.hDevMode = PrinterSettings.GetHdevmode(PageSettings);
                }

                data.hDevNames = PrinterSettings.GetHdevnames();
            }
            catch (InvalidPrinterException)
            {
                data.hDevMode  = IntPtr.Zero;
                data.hDevNames = IntPtr.Zero;
                // Leave those fields null; Windows will fill them in
            }

            try
            {
                // Windows doesn't like it if page numbers are invalid
                if (AllowSomePages)
                {
                    if (PrinterSettings.FromPage < PrinterSettings.MinimumPage ||
                        PrinterSettings.FromPage > PrinterSettings.MaximumPage)
                    {
                        throw new ArgumentException(string.Format(SR.PDpageOutOfRange, "FromPage"));
                    }

                    if (PrinterSettings.ToPage < PrinterSettings.MinimumPage ||
                        PrinterSettings.ToPage > PrinterSettings.MaximumPage)
                    {
                        throw new ArgumentException(string.Format(SR.PDpageOutOfRange, "ToPage"));
                    }

                    if (PrinterSettings.ToPage < PrinterSettings.FromPage)
                    {
                        throw new ArgumentException(string.Format(SR.PDpageOutOfRange, "FromPage"));
                    }

                    data.nFromPage = (short)PrinterSettings.FromPage;
                    data.nToPage   = (short)PrinterSettings.ToPage;
                    data.nMinPage  = (short)PrinterSettings.MinimumPage;
                    data.nMaxPage  = (short)PrinterSettings.MaximumPage;
                }

                if (!UnsafeNativeMethods.PrintDlg(data))
                {
                    return(false);
                }

                UpdatePrinterSettings(data.hDevMode, data.hDevNames, data.nCopies, data.Flags, settings, PageSettings);

                PrintToFile = ((data.Flags & NativeMethods.PD_PRINTTOFILE) != 0);
                PrinterSettings.PrintToFile = PrintToFile;

                if (AllowSomePages)
                {
                    PrinterSettings.FromPage = data.nFromPage;
                    PrinterSettings.ToPage   = data.nToPage;
                }

                // When the flag PD_USEDEVMODECOPIESANDCOLLATE is not set,
                // PRINTDLG.nCopies or PRINTDLG.nCopies indicates the number of copies the user wants
                // to print, and the PD_COLLATE flag in the Flags member indicates
                // whether the user wants to print them collated.
                if ((data.Flags & NativeMethods.PD_USEDEVMODECOPIESANDCOLLATE) == 0)
                {
                    PrinterSettings.Copies  = data.nCopies;
                    PrinterSettings.Collate = ((data.Flags & NativeMethods.PD_COLLATE) == NativeMethods.PD_COLLATE);
                }

                return(true);
            }
            finally
            {
                UnsafeNativeMethods.GlobalFree(new HandleRef(data, data.hDevMode));
                UnsafeNativeMethods.GlobalFree(new HandleRef(data, data.hDevNames));
            }
        }
Ejemplo n.º 39
0
        /// <include file='doc\PrintDialog.uex' path='docs/doc[@for="PrintDialog.RunDialog"]/*' />
        /// <devdoc>
        /// </devdoc>
        /// <internalonly/>
        // VSWhidbey 93449: Use PrintDlgEx and PRINTDLGEX on Win2k and newer OS'.
        protected override bool RunDialog(IntPtr hwndOwner) {
            bool returnValue = false;

            IntSecurity.SafePrinting.Demand();

            NativeMethods.WndProc hookProcPtr = new NativeMethods.WndProc(this.HookProc);

            if (!UseEXDialog || (Environment.OSVersion.Platform != System.PlatformID.Win32NT ||
                Environment.OSVersion.Version.Major < 5)) {
                NativeMethods.PRINTDLG data = CreatePRINTDLG();
                returnValue = ShowPrintDialog(hwndOwner, hookProcPtr, data);
            }
            else {
                NativeMethods.PRINTDLGEX data = CreatePRINTDLGEX();
                returnValue = ShowPrintDialog(hwndOwner, data);
            }

            return returnValue;
        }
Ejemplo n.º 40
0
        internal IntPtr CriticalAttach( IntPtr hwnd )
        {
            if(hwnd == IntPtr.Zero)
            {
                throw new ArgumentNullException("hwnd");
            }
            if(_bond != Bond.Unattached)
            {
                throw new InvalidOperationException();
            }

            NativeMethods.WndProc newWndProc = new NativeMethods.WndProc(SubclassWndProc);
            IntPtr oldWndProc = UnsafeNativeMethods.GetWindowLongPtr(new HandleRef(this,hwnd), NativeMethods.GWL_WNDPROC);
            HookWindowProc(hwnd, newWndProc, oldWndProc);

            // Return the GC handle as a unique identifier of this
            return (IntPtr) _gcHandle;
        }
Ejemplo n.º 41
0
        /// <include file='doc\ColorDialog.uex' path='docs/doc[@for="ColorDialog.RunDialog"]/*' />
        /// <devdoc>
        /// </devdoc>
        /// <internalonly/>
        protected override bool RunDialog(IntPtr hwndOwner) {

            NativeMethods.WndProc hookProcPtr = new NativeMethods.WndProc(this.HookProc);
            NativeMethods.CHOOSECOLOR cc = new NativeMethods.CHOOSECOLOR();
            IntPtr custColorPtr = Marshal.AllocCoTaskMem(64);
            try {
                Marshal.Copy(customColors, 0, custColorPtr, 16);
                cc.hwndOwner = hwndOwner;
                cc.hInstance = Instance;
                cc.rgbResult = ColorTranslator.ToWin32(color);
                cc.lpCustColors = custColorPtr;

                int flags = Options | (NativeMethods.CC_RGBINIT | NativeMethods.CC_ENABLEHOOK);
                // Our docs say AllowFullOpen takes precedence over FullOpen; ChooseColor implements the opposite
                if (!AllowFullOpen)
                    flags &= ~NativeMethods.CC_FULLOPEN;
                cc.Flags = flags;

                cc.lpfnHook = hookProcPtr;
                if (!SafeNativeMethods.ChooseColor(cc)) return false;
                if (cc.rgbResult != ColorTranslator.ToWin32(color)) color = ColorTranslator.FromOle(cc.rgbResult);
                Marshal.Copy(custColorPtr, customColors, 0, 16);
                return true;
            }
            finally {
                Marshal.FreeCoTaskMem(custColorPtr);
            }
        }
Ejemplo n.º 42
0
        /// <include file='doc\FontDialog.uex' path='docs/doc[@for="FontDialog.RunDialog"]/*' />
        /// <internalonly/>
        /// <devdoc>
        ///    <para>
        ///       The actual implementation of running the dialog. Inheriting classes
        ///       should override this if they want to add more functionality, and call
        ///       base.runDialog() if necessary
        ///
        ///    </para>
        /// </devdoc>
        protected override bool RunDialog(IntPtr hWndOwner)
        {
            NativeMethods.WndProc    hookProcPtr = new NativeMethods.WndProc(this.HookProc);
            NativeMethods.CHOOSEFONT cf          = new NativeMethods.CHOOSEFONT();
            IntPtr screenDC = UnsafeNativeMethods.GetDC(NativeMethods.NullHandleRef);

            NativeMethods.LOGFONT lf = new NativeMethods.LOGFONT();

            Graphics graphics = Graphics.FromHdcInternal(screenDC);

            try {
                Font.ToLogFont(lf, graphics);
            }
            finally {
                graphics.Dispose();
            }
            UnsafeNativeMethods.ReleaseDC(NativeMethods.NullHandleRef, new HandleRef(null, screenDC));

            IntPtr logFontPtr = IntPtr.Zero;

            try {
                logFontPtr = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(NativeMethods.LOGFONT)));
                Marshal.StructureToPtr(lf, logFontPtr, false);

                cf.lStructSize = Marshal.SizeOf(typeof(NativeMethods.CHOOSEFONT));
                cf.hwndOwner   = hWndOwner;
                cf.hDC         = IntPtr.Zero;
                cf.lpLogFont   = logFontPtr;
                cf.Flags       = Options | NativeMethods.CF_INITTOLOGFONTSTRUCT | NativeMethods.CF_ENABLEHOOK;
                if (minSize > 0 || maxSize > 0)
                {
                    cf.Flags |= NativeMethods.CF_LIMITSIZE;
                }

                //if ShowColor=true then try to draw the sample text in color,
                //if ShowEffects=false then we will draw the sample text in standard control text color regardless.
                //(limitation of windows control)
                //
                if (ShowColor || ShowEffects)
                {
                    cf.rgbColors = ColorTranslator.ToWin32(color);
                }
                else
                {
                    cf.rgbColors = ColorTranslator.ToWin32(SystemColors.ControlText);
                }

                cf.lpfnHook  = hookProcPtr;
                cf.hInstance = UnsafeNativeMethods.GetModuleHandle(null);
                cf.nSizeMin  = minSize;
                if (maxSize == 0)
                {
                    cf.nSizeMax = int.MaxValue;
                }
                else
                {
                    cf.nSizeMax = maxSize;
                }
                Debug.Assert(cf.nSizeMin <= cf.nSizeMax, "min and max font sizes are the wrong way around");
                if (!SafeNativeMethods.ChooseFont(cf))
                {
                    return(false);
                }


                NativeMethods.LOGFONT lfReturned = null;
                lfReturned = (NativeMethods.LOGFONT)UnsafeNativeMethods.PtrToStructure(logFontPtr, typeof(NativeMethods.LOGFONT));

                if (lfReturned.lfFaceName != null && lfReturned.lfFaceName.Length > 0)
                {
                    lf = lfReturned;
                    UpdateFont(lf);
                    UpdateColor(cf.rgbColors);
                }

                return(true);
            }
            finally {
                if (logFontPtr != IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(logFontPtr);
                }
            }
        }
Ejemplo n.º 43
0
        public HwndWrapper(
            int classStyle,
            int style,
            int exStyle,
            int x,
            int y,
            int width,
            int height,
            string name,
            IntPtr parent,
            HwndWrapperHook[] hooks)
        {

            _ownerThreadID = new SecurityCriticalDataForSet<int>(Thread.CurrentThread.ManagedThreadId);


            // First, add the set of hooks.  This allows the hooks to receive the
            // messages sent to the window very early in the process.
            if(hooks != null)
            {
                for(int i = 0, iEnd = hooks.Length; i < iEnd; i++)
                {
                    if(null != hooks[i])
                        AddHook(hooks[i]);
                }
            }


            _wndProc = new SecurityCriticalData<HwndWrapperHook>(new HwndWrapperHook(WndProc));

            // We create the HwndSubclass object so that we can use its
            // window proc directly.  We will not be "subclassing" the
            // window we create.
            HwndSubclass hwndSubclass = new HwndSubclass(_wndProc.Value);
            
            // Register a unique window class for this instance.
            NativeMethods.WNDCLASSEX_D wc_d = new NativeMethods.WNDCLASSEX_D();

            IntPtr hNullBrush = UnsafeNativeMethods.CriticalGetStockObject(NativeMethods.NULL_BRUSH);

            if (hNullBrush == IntPtr.Zero)
            {
                throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
            }

            IntPtr hInstance = UnsafeNativeMethods.GetModuleHandle( null );

            // We need to keep the Delegate object alive through the call to CreateWindowEx().
            // Subclass.WndProc will install a better delegate (to the same function) when it
            // processes the first message.
            // But this first delegate needs be held alive until then.
            NativeMethods.WndProc initialWndProc = new NativeMethods.WndProc(hwndSubclass.SubclassWndProc);

            // The class name is a concat of AppName, ThreadName, and RandomNumber.
            // Register will fail if the string gets over 255 in length.
            // So limit each part to a reasonable amount.
            string appName;
            if(null != AppDomain.CurrentDomain.FriendlyName && 128 <= AppDomain.CurrentDomain.FriendlyName.Length)
                appName = AppDomain.CurrentDomain.FriendlyName.Substring(0, 128);
            else
                appName = AppDomain.CurrentDomain.FriendlyName;

            string threadName;
            if(null != Thread.CurrentThread.Name && 64 <= Thread.CurrentThread.Name.Length)
                threadName = Thread.CurrentThread.Name.Substring(0, 64);
            else
                threadName = Thread.CurrentThread.Name;

            // Create a suitable unique class name.
            _classAtom = 0;
            string randomName = Guid.NewGuid().ToString();
            string className = String.Format(CultureInfo.InvariantCulture, "HwndWrapper[{0};{1};{2}]", appName, threadName, randomName);

            wc_d.cbSize        = Marshal.SizeOf(typeof(NativeMethods.WNDCLASSEX_D));
            wc_d.style         = classStyle;
            wc_d.lpfnWndProc   = initialWndProc;
            wc_d.cbClsExtra    = 0;
            wc_d.cbWndExtra    = 0;
            wc_d.hInstance     = hInstance;
            wc_d.hIcon         = IntPtr.Zero;
            wc_d.hCursor       = IntPtr.Zero;
            wc_d.hbrBackground = hNullBrush;
            wc_d.lpszMenuName  = "";
            wc_d.lpszClassName = className;
            wc_d.hIconSm       = IntPtr.Zero;

            // Register the unique class for this instance.
            // Note we use a GUID in the name so we are confident that
            // the class name should be unique.  And RegisterClassEx won't
            // fail (for that reason).
            _classAtom = UnsafeNativeMethods.RegisterClassEx(wc_d);

            // call CreateWindow
            _isInCreateWindow = true;
            try {
                _handle = new SecurityCriticalDataClass<IntPtr>(UnsafeNativeMethods.CreateWindowEx(exStyle,
                                                         className,
                                                         name,
                                                         style,
                                                         x,
                                                         y,
                                                         width,
                                                         height,
                                                         new HandleRef(null,parent),
                                                         new HandleRef(null,IntPtr.Zero),
                                                         new HandleRef(null,IntPtr.Zero),
                                                         null));
            }
            finally
            {
                _isInCreateWindow = false;
                if(_handle == null || _handle.Value == IntPtr.Zero)
                {
                    new UIPermission(UIPermissionWindow.AllWindows).Assert(); //BlessedAssert to call Dispose
                    try
                    {
                        // Because the HwndSubclass is pinned, but the HWND creation failed,
                        // we need to manually clean it up.
                        hwndSubclass.Dispose();
                    }
                    finally
                    {
                        CodeAccessPermission.RevertAssert();
                    }
                }
            }
            GC.KeepAlive(initialWndProc);
        }