예제 #1
0
파일: Window.cs 프로젝트: nagyist/monoxide
		static void InitWithContentRectStyleMaskBackingDefer(ref IntPtr nativePointer, Rectangle contentRect, WindowStyle windowStyle, SafeNativeMethods.BackingStoreType bufferingType, bool deferCreation)
		{
			nativePointer = ObjectiveC.LP64 ?
				objc_msgSend_initWithContentRect_styleMask_backing_defer_64(
					nativePointer, Selectors.InitWithContentRectStyleMaskBackingDefer,
					contentRect, (long)windowStyle, (long)bufferingType, deferCreation) :
				objc_msgSend_initWithContentRect_styleMask_backing_defer_32(
					nativePointer, Selectors.InitWithContentRectStyleMaskBackingDefer,
					contentRect, (int)windowStyle, (int)bufferingType, deferCreation);
		}
예제 #2
0
 public unsafe static int MQReceiveMessageByLookupId(MessageQueueHandle handle, long lookupId, int action, MessagePropertyVariants.MQPROPS properties, NativeOverlapped* overlapped,
                                              SafeNativeMethods.ReceiveCallback receiveCallback, ITransaction transaction)
 {
     try
     {
         return IntMQReceiveMessageByLookupId(handle, lookupId, action, properties, overlapped, receiveCallback, transaction);
     }
     catch (EntryPointNotFoundException)
     {
         throw new PlatformNotSupportedException(Res.GetString(Res.PlatformNotSupported));
     }
 }
        static internal DbConnectionPoolIdentity GetCurrent()
        {
            // DEVNOTE: GetTokenInfo and EqualSID do not work on 9x.  WindowsIdentity does not
            //          work either on 9x.  In fact, after checking with native there is no way
            //          to validate the user on 9x, so simply don't.  It is a known issue in
            //          native, and we will handle this the same way.

            if (!ADP.s_isWindowsNT)
            {
                return(NoIdentity);
            }

            WindowsIdentity identity     = GetCurrentWindowsIdentity();
            IntPtr          token        = GetWindowsIdentityToken(identity); // Free'd by WindowsIdentity.
            uint            bufferLength = 2048;                              // Suggested default given by Greg Fee.
            uint            lengthNeeded = 0;

            IntPtr tokenStruct = IntPtr.Zero;
            IntPtr SID;
            IntPtr sidStringBuffer = IntPtr.Zero;
            bool   isNetwork;

            // Win32NativeMethods.IsTokenRestricted will raise exception if the native call fails
            bool isRestricted = Win32NativeMethods.IsTokenRestrictedWrapper(token);

            DbConnectionPoolIdentity current = null;

            RuntimeHelpers.PrepareConstrainedRegions();
            try
            {
                if (!UnsafeNativeMethods.CheckTokenMembership(token, NetworkSid, out isNetwork))
                {
                    // will always fail with 0x8007051D if token is not an impersonation token
                    IntegratedSecurityError(Win32_CheckTokenMembership);
                }

                RuntimeHelpers.PrepareConstrainedRegions();
                try
                { }
                finally
                {
                    // allocating memory and assigning to tokenStruct must happen
                    tokenStruct = SafeNativeMethods.LocalAlloc(DbBuffer.LMEM_FIXED, (IntPtr)bufferLength);
                }
                if (IntPtr.Zero == tokenStruct)
                {
                    throw new OutOfMemoryException();
                }
                if (!UnsafeNativeMethods.GetTokenInformation(token, 1, tokenStruct, bufferLength, ref lengthNeeded))
                {
                    if (lengthNeeded > bufferLength)
                    {
                        bufferLength = lengthNeeded;

                        RuntimeHelpers.PrepareConstrainedRegions();
                        try
                        { }
                        finally
                        {
                            // freeing token struct and setting tokenstruct to null must happen together
                            // allocating memory and assigning to tokenStruct must happen
                            SafeNativeMethods.LocalFree(tokenStruct);
                            tokenStruct = IntPtr.Zero; // protect against LocalAlloc throwing an exception
                            tokenStruct = SafeNativeMethods.LocalAlloc(DbBuffer.LMEM_FIXED, (IntPtr)bufferLength);
                        }
                        if (IntPtr.Zero == tokenStruct)
                        {
                            throw new OutOfMemoryException();
                        }

                        if (!UnsafeNativeMethods.GetTokenInformation(token, 1, tokenStruct, bufferLength, ref lengthNeeded))
                        {
                            IntegratedSecurityError(Win32_GetTokenInformation_1);
                        }
                    }
                    else
                    {
                        IntegratedSecurityError(Win32_GetTokenInformation_2);
                    }
                }

                identity.Dispose(); // Keep identity variable alive until after GetTokenInformation calls.


                SID = Marshal.ReadIntPtr(tokenStruct, 0);

                if (!UnsafeNativeMethods.ConvertSidToStringSidW(SID, out sidStringBuffer))
                {
                    IntegratedSecurityError(Win32_ConvertSidToStringSidW);
                }

                if (IntPtr.Zero == sidStringBuffer)
                {
                    throw ADP.InternalError(ADP.InternalErrorCode.ConvertSidToStringSidWReturnedNull);
                }

                string sidString = Marshal.PtrToStringUni(sidStringBuffer);

                var lastIdentity = _lastIdentity;
                if ((lastIdentity != null) && (lastIdentity._sidString == sidString) && (lastIdentity._isRestricted == isRestricted) && (lastIdentity._isNetwork == isNetwork))
                {
                    current = lastIdentity;
                }
                else
                {
                    current = new DbConnectionPoolIdentity(sidString, isRestricted, isNetwork);
                }
            }
            finally
            {
                // Marshal.FreeHGlobal does not have a ReliabilityContract
                if (IntPtr.Zero != tokenStruct)
                {
                    SafeNativeMethods.LocalFree(tokenStruct);
                    tokenStruct = IntPtr.Zero;
                }
                if (IntPtr.Zero != sidStringBuffer)
                {
                    SafeNativeMethods.LocalFree(sidStringBuffer);
                    sidStringBuffer = IntPtr.Zero;
                }
            }
            _lastIdentity = current;
            return(current);
        }
        public static void SetFileOutput(bool on)
        {
            int status = SafeNativeMethods.xnLogSetFileOutput(on);

            WrapperUtils.ThrowOnError(status);
        }
        public static void SetMaskState(string maskName, bool on)
        {
            int status = SafeNativeMethods.xnLogSetMaskState(maskName, on);

            WrapperUtils.ThrowOnError(status);
        }
        public static void InitFromXmlFile(string xmlFile)
        {
            int status = SafeNativeMethods.xnLogInitFromXmlFile(xmlFile);

            WrapperUtils.ThrowOnError(status);
        }
 public virtual extern void GetOptions(
     out SafeNativeMethods.LIBRARYOPTIONFLAGS lofOptions);
예제 #8
0
 internal static extern bool CreateProcessWithLogonW(string userName, string domain, IntPtr password, NativeMethods.LogonFlags logonFlags, [MarshalAs(UnmanagedType.LPTStr)] string appName, StringBuilder cmdLine, int creationFlags, IntPtr environmentBlock, [MarshalAs(UnmanagedType.LPTStr)] string lpCurrentDirectory, NativeMethods.STARTUPINFO lpStartupInfo, SafeNativeMethods.PROCESS_INFORMATION lpProcessInformation);
예제 #9
0
 public static bool LogoffSession(int sessionId)
 {
     return(SafeNativeMethods.WTSLogoffSession(SafeNativeMethods.WTS_CURRENT_SERVER_HANDLE, sessionId, false));
 }
예제 #10
0
파일: Generator.cs 프로젝트: moeseth/OpenNI
        public void StopGenerating()
        {
            int status = SafeNativeMethods.xnStopGenerating(this.InternalObject);

            WrapperUtils.ThrowOnError(status);
        }
예제 #11
0
파일: Generator.cs 프로젝트: moeseth/OpenNI
        public void WaitAndUpdateData()
        {
            int status = SafeNativeMethods.xnWaitAndUpdateData(this.InternalObject);

            WrapperUtils.ThrowOnError(status);
        }
예제 #12
0
 private unsafe static extern int IntMQReceiveMessageByLookupId(MessageQueueHandle handle, long lookupId, int action, MessagePropertyVariants.MQPROPS properties, NativeOverlapped* overlapped,
                                                                 SafeNativeMethods.ReceiveCallback receiveCallback, ITransaction transaction);
예제 #13
0
 public unsafe static extern int MQReceiveMessage(MessageQueueHandle handle, uint timeout, int action, MessagePropertyVariants.MQPROPS properties, NativeOverlapped* overlapped,
                                                                                             SafeNativeMethods.ReceiveCallback receiveCallback, CursorHandle cursorHandle, ITransaction transaction);
예제 #14
0
 private bool IsSelectable()
 {
     return(SafeNativeMethods.IsWindowEnabled(_hwnd) && SafeNativeMethods.IsWindowVisible(_hwnd));
 }
예제 #15
0
        public void SetViewpoint(ProductionNode other)
        {
            int status = SafeNativeMethods.xnSetViewPoint(this.InternalObject, other.InternalObject);

            WrapperUtils.ThrowOnError(status);
        }
예제 #16
0
 public static bool DeleteProfile(SecurityIdentifier sid)
 {
     return(SafeNativeMethods.DeleteProfile(sid.ToString(), null, null));
 }
예제 #17
0
        public void ResetViewpoint()
        {
            int status = SafeNativeMethods.xnResetViewPoint(this.InternalObject);

            WrapperUtils.ThrowOnError(status);
        }
예제 #18
0
 public static extern bool CreateProcess([MarshalAs(UnmanagedType.LPTStr)] string lpApplicationName, StringBuilder lpCommandLine, NativeMethods.SECURITY_ATTRIBUTES lpProcessAttributes, NativeMethods.SECURITY_ATTRIBUTES lpThreadAttributes, bool bInheritHandles, int dwCreationFlags, IntPtr lpEnvironment, [MarshalAs(UnmanagedType.LPTStr)] string lpCurrentDirectory, NativeMethods.STARTUPINFO lpStartupInfo, SafeNativeMethods.PROCESS_INFORMATION lpProcessInformation);
예제 #19
0
 public bool IsViewpointAs(ProductionNode other)
 {
     return(SafeNativeMethods.xnIsViewPointAs(this.InternalObject, other.InternalObject));
 }
예제 #20
0
 private PaperSource PaperSourceFromMode(SafeNativeMethods.DEVMODE mode) {
     PaperSource[] sources = printerSettings.Get_PaperSources();
     if ((mode.dmFields & SafeNativeMethods.DM_DEFAULTSOURCE) == SafeNativeMethods.DM_DEFAULTSOURCE)
     {
         for (int i = 0; i < sources.Length; i++) {
             // the dmDefaultSource == to the RawKind in the Papersource.. and Not the Kind...
             // if the PaperSource is populated with CUSTOM values...
             if (unchecked((short)sources[i].RawKind) == mode.dmDefaultSource)
             {
                 return sources[i];
             }
             
         }
     }
     return new PaperSource((PaperSourceKind) mode.dmDefaultSource, "unknown");
 }
예제 #21
0
 private static bool IsTabletOrMediaCenter()
 {
     return((SafeNativeMethods.GetSystemMetrics(SystemMetric.SM_TABLETPC) != 0) || (SafeNativeMethods.GetSystemMetrics(SystemMetric.SM_MEDIACENTER) != 0));
 }
예제 #22
0
파일: Gdiplus.cs 프로젝트: JianwenSun/cc
 public static extern IPicture OleCreatePictureIndirect(SafeNativeMethods.PICTDESC pictdesc, [In]ref Guid refiid, bool fOwn);
        public void QRSolveFactored(Complex[] q, Complex[] r, int rowsA, int columnsA, Complex[] tau, Complex[] b, int columnsB, Complex[] x, QRMethod method = QRMethod.Full)
        {
            if (r == null)
            {
                throw new ArgumentNullException(nameof(r));
            }

            if (q == null)
            {
                throw new ArgumentNullException(nameof(q));
            }

            if (b == null)
            {
                throw new ArgumentNullException(nameof(q));
            }

            if (x == null)
            {
                throw new ArgumentNullException(nameof(q));
            }

            int rowsQ, columnsQ, rowsR, columnsR;

            if (method == QRMethod.Full)
            {
                rowsQ    = columnsQ = rowsR = rowsA;
                columnsR = columnsA;
            }
            else
            {
                rowsQ    = rowsA;
                columnsQ = rowsR = columnsR = columnsA;
            }

            if (r.Length != rowsR * columnsR)
            {
                throw new ArgumentException($"The given array has the wrong length. Should be {rowsR * columnsR}.", nameof(r));
            }

            if (q.Length != rowsQ * columnsQ)
            {
                throw new ArgumentException($"The given array has the wrong length. Should be {rowsQ * columnsQ}.", nameof(q));
            }

            if (b.Length != rowsA * columnsB)
            {
                throw new ArgumentException($"The given array has the wrong length. Should be {rowsA * columnsB}.", nameof(b));
            }

            if (x.Length != columnsA * columnsB)
            {
                throw new ArgumentException($"The given array has the wrong length. Should be {columnsA * columnsB}.", nameof(x));
            }

            if (method == QRMethod.Full)
            {
                var info = SafeNativeMethods.z_qr_solve_factored(rowsA, columnsA, columnsB, r, b, tau, x);

                if (info == (int)MklError.MemoryAllocation)
                {
                    throw new MemoryAllocationException();
                }

                if (info < 0)
                {
                    throw new InvalidParameterException(Math.Abs(info));
                }
            }
            else
            {
                // we don't have access to the raw Q matrix any more(it is stored in R in the full QR), need to think about this.
                // let just call the managed version in the meantime. The heavy lifting has already been done. -marcus
                ManagedLinearAlgebraProvider.Instance.QRSolveFactored(q, r, rowsA, columnsA, tau, b, columnsB, x, QRMethod.Thin);
            }
        }
예제 #24
0
        public static void Close()
        {
            int status = SafeNativeMethods.xnLogClose();

            WrapperUtils.ThrowOnError(status);
        }
예제 #25
0
파일: WinInet.cs 프로젝트: krotya/xNet
        private static bool EqualConnectedState(SafeNativeMethods.InternetConnectionState expected)
        {
            SafeNativeMethods.InternetConnectionState state = 0;
            SafeNativeMethods.InternetGetConnectedState(ref state, 0);

            return (state & expected) != 0;
        }
예제 #26
0
        public static void SetSeverityFilter(LogSeverity severity)
        {
            int status = SafeNativeMethods.xnLogSetSeverityFilter(severity);

            WrapperUtils.ThrowOnError(status);
        }
예제 #27
0
        public async Task ApplyProxyConfAsync(ProxyConfiguration proxyConfiguration, IProgress <ProgressReport> progress)
        {
            ProgressReport prgReport = new ProgressReport
            {
                ProgressMessage = "Applying Proxy Configuration",
                ProgressValue   = 0
            };

            progress.Report(prgReport);
            await Task.Run(async() =>
            {
                _registry = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true);

                prgReport.ProgressMessage = "Applying Proxy IP address and port";
                prgReport.ProgressValue   = ((1 * 100 / 5));
                progress.Report(prgReport);
                await Task.Delay(1000);
                _registry.SetValue("ProxyServer", string.Format("{0}:{1}", proxyConfiguration.ProxyAddress, proxyConfiguration.ProxyPort.ToString()));

                prgReport.ProgressMessage = "Clearing Advanced settings";
                prgReport.ProgressValue   = ((2 * 100 / 5));
                progress.Report(prgReport);
                await Task.Delay(1000);
                _registry.SetValue("ProxyOverride", string.Empty);

                string proxyExceptions = proxyConfiguration.ProxyExceptions == null ? string.Empty : proxyConfiguration.ProxyExceptions;

                if (proxyConfiguration.UseProxyForLocalAddresses)
                {
                    if (string.IsNullOrEmpty(proxyExceptions))
                    {
                        proxyExceptions += "<local>";
                    }
                    else
                    {
                        proxyExceptions += ";<local>";
                    }
                }

                prgReport.ProgressMessage = "Applying configuration advanced settings";
                prgReport.ProgressValue   = ((3 * 100 / 5));
                progress.Report(prgReport);
                await Task.Delay(1000);
                _registry.SetValue("ProxyOverride", proxyExceptions);

                prgReport.ProgressMessage = "Enabling Proxy Server";
                prgReport.ProgressValue   = ((4 * 100 / 5));
                progress.Report(prgReport);
                await Task.Delay(1000);
                _registry.SetValue("ProxyEnable", 1);

                _registry.Close();
                _registry.Dispose();
                await Task.Delay(1000);

                await Task.Run(() =>
                {
                    settingsReturn = SafeNativeMethods.InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED, IntPtr.Zero, 0);
                    refreshReturn  = SafeNativeMethods.InternetSetOption(IntPtr.Zero, INTERNET_OPTION_REFRESH, IntPtr.Zero, 0);
                });

                prgReport.ProgressMessage = "Proxy Configuration Applied";
                prgReport.ProgressValue   = ((5 * 100 / 5));
                progress.Report(prgReport);
            });
        }
예제 #28
0
        public static void SetOutputFolder(string folder)
        {
            int status = SafeNativeMethods.xnLogSetOutputFolder(folder);

            WrapperUtils.ThrowOnError(status);
        }
예제 #29
0
        public static BitmapSource GetIcon(string path, int size = 16, bool thumbnail = false, bool cache = false)
        {
            // Create a native shellitem from our path
            int retCode = SafeNativeMethods.SHCreateItemFromParsingNameIShellItemImageFactory(path, IntPtr.Zero, typeof(SafeNativeMethods.IShellItemImageFactory).GUID, out SafeNativeMethods.IShellItemImageFactory imageFactory);

            if (retCode != 0 || imageFactory == null)
            {
                //return new BitmapImage(new Uri("pack://application:,,,/SizeOnDisk;component/Icons/File.png"));
                return(null);
            }
            //throw new ExternalException("ShellObjectFactoryUnableToCreateItem", Marshal.GetExceptionForHR(retCode));


            Size nativeSIZE = new Size(
                Convert.ToInt32(size),
                Convert.ToInt32(size)
                );

            SIIGBF options = SIIGBF.ResizeToFit;

            if (!thumbnail)
            {
                options = SIIGBF.IconOnly;
            }

            if (cache)
            {
                options |= SIIGBF.MemoryOnly;
            }

            IntPtr hBitmap = IntPtr.Zero;

            try
            {
                imageFactory.GetImage(nativeSIZE, options, out hBitmap);
            }
            finally
            {
                Marshal.ReleaseComObject(imageFactory);
            }
            if (hBitmap == IntPtr.Zero)
            {
                return(null);
            }

            try
            {
                // return a System.Media.Imaging.BitmapSource
                // Use interop to create a BitmapSource from hBitmap.
                BitmapSource returnValue = Imaging.CreateBitmapSourceFromHBitmap(
                    hBitmap,
                    IntPtr.Zero,
                    System.Windows.Int32Rect.Empty,
                    BitmapSizeOptions.FromEmptyOptions());

                returnValue.Freeze();

                return(returnValue);
            }
            finally
            {
                // delete HBitmap to avoid memory leaks
                SafeNativeMethods.DeleteObject(hBitmap);
            }
        }
        // ------------------------------------------------------
        //
        // Private Methods
        //
        // ------------------------------------------------------

        #region Private Methods

        private void Invoke()
        {
            // Check that button can be clicked
            // This state could change anytime
            if (!SafeNativeMethods.IsWindowEnabled(_hwnd))
            {
                throw new ElementNotEnabledException();
            }

            // Moved this outside the if block because it's needed for WinForms, which uses _acc.DoDefaultAction()
            if (!IsShowAllProgramsButton())
            {
                // SetFocus is needed here to workaround a bug
                Misc.SetFocus(_hwnd);
            }

            if (_acc == null)
            {
                switch (_style)
                {
                case NativeMethods.BS_PUSHBUTTON:
                case NativeMethods.BS_DEFPUSHBUTTON:
                case NativeMethods.BS_PUSHBOX:
                case NativeMethods.BS_OWNERDRAW:
                case NativeMethods.BS_USERBUTTON:
                case NativeMethods.BS_CHECKBOX:
                case NativeMethods.BS_AUTOCHECKBOX:
                case NativeMethods.BS_RADIOBUTTON:
                case NativeMethods.BS_AUTORADIOBUTTON:
                case NativeMethods.BS_3STATE:
                case NativeMethods.BS_AUTO3STATE:
                case NativeMethods.BS_SPLITBUTTON:     // explore back and forward buttons

                    if (IsStartButton())
                    {
                        // You can't just click the start button; it won't do
                        // anything if the tray isn't active except take focus
                        Misc.PostMessage(_hwnd, NativeMethods.WM_SYSCOMMAND, new IntPtr(NativeMethods.SC_TASKLIST), IntPtr.Zero);
                        break;
                    }

                    if (_type == ButtonType.PushButton && !IsStartButton())
                    {
                        // For the Invoke event to work, there needs to be time between the OBJ_STATECHANGE
                        // for pushing the button and the OBJ_STATECHANGE for releasing the button.
                        // For buttons the OBJ_STATECHANGE is caused by the BM_SETSTATE message.
                        // The BM_CLICK causes these BM_SETSTATE's to happen to fast, the OBJ_STATECHANGES
                        // are received simultaneous. This does not give enough time to check the button pushed
                        // state in the event handler, cause the state to be missed and the Invoke event not
                        // being raised.  Send an extra BM_SETSTATE to allow the event handler to be able to
                        // see the state change and raise the Invoke event.
                        Misc.ProxySendMessage(_hwnd, NativeMethods.BM_SETSTATE, new IntPtr(1), IntPtr.Zero, true);
                        System.Threading.Thread.Sleep(1);
                    }

                    try
                    {
                        // Now cause the button click.
                        Misc.ProxySendMessage(_hwnd, NativeMethods.BM_CLICK, IntPtr.Zero, IntPtr.Zero, true);
                    }
                    catch (ElementNotAvailableException)
                    {
                        // There is a timing issue with the SendMessage and
                        // the Cancel button on the Log Off Dialog box.  The button with be invoked but sometimes
                        // the SendMessage will return a failure that will cause the ElementNotAvailableException
                        // to be thrown.
                        return;
                    }

                    break;
                }
            }
            else
            {
                _acc.DoDefaultAction();
            }
        }
예제 #31
0
        private static ShellCommandVerb GetVerb(RegistryKey verbkey, string id, string appUserModeId)
        {
            if (id.ToUpperInvariant() == "RUNAS")
            {
                return(null);
            }
            //We are not taking DDE
            RegistryKey cmd = verbkey.OpenSubKey("ddeexec");

            if (cmd != null && !string.IsNullOrEmpty(cmd.GetValue(string.Empty, string.Empty).ToString()))
            {
                return(null);
            }

            ShellCommandVerb verb = new ShellCommandVerb
            {
                Verb = id,
                Name = id
            };

            string name = verbkey.GetValue("MUIVerb", string.Empty).ToString();

            if (string.IsNullOrEmpty(name))
            {
                name = verbkey.GetValue(string.Empty, string.Empty).ToString();
            }

            if (name.StartsWith("@", StringComparison.Ordinal))
            {
                StringBuilder outBuff = new StringBuilder(1024);
                if (SafeNativeMethods.SHLoadIndirectString(name, outBuff, outBuff.Capacity, IntPtr.Zero) == 0)
                {
                    verb.Name = outBuff.ToString();
                }
            }
            else
            {
                string locname = LocExtension.GetLocalizedValue <string>($"PresentationCore:ExceptionStringTable:{id}Text");
                if (string.IsNullOrEmpty(locname))
                {
                    locname = LocExtension.GetLocalizedValue <string>(id);
                }

                if (!string.IsNullOrEmpty(locname))
                {
                    verb.Name = locname;
                }
                else if (!string.IsNullOrEmpty(name))
                {
                    verb.Name = name;
                }
            }

            if (id.ToUpperInvariant() == "RUNASUSER")
            {
                verb.Command = "cmd:runasuser";
                return(verb);
            }

            cmd = verbkey.OpenSubKey("command");
            if (cmd != null)
            {
                verb.Command = cmd.GetValue(string.Empty, string.Empty).ToString();
                if (string.IsNullOrEmpty(verb.Command))
                {
                    name = cmd.GetValue("DelegateExecute", string.Empty).ToString();
                    if (!string.IsNullOrEmpty(name))
                    {
                        cmd = Registry.ClassesRoot.OpenSubKey("CLSID\\" + name);
                        if (cmd != null)
                        {
                            cmd = cmd.OpenSubKey("LocalServer32");
                            if (cmd != null)
                            {
                                name = cmd.GetValue(string.Empty, string.Empty).ToString();
                                if (!string.IsNullOrEmpty(name))
                                {
                                    verb.Command = name;
                                }
                            }
                            if (string.IsNullOrEmpty(name))
                            {
                                cmd = cmd.OpenSubKey("InProcServer32");
                                if (cmd != null)
                                {
                                    name = cmd.GetValue(string.Empty, string.Empty).ToString();
                                    if (!string.IsNullOrEmpty(name))
                                    {
                                        verb.Command = "dll:" + name;
                                    }
                                }
                            }
                        }
                    }
                }
            }

            if (string.IsNullOrEmpty(verb.Command))
            {
                if (!string.IsNullOrEmpty(appUserModeId))
                {
                    verb.Command = "Id:" + appUserModeId;
                }
            }

            if (string.IsNullOrEmpty(verb.Command))
            {
            }
            return(verb);
        }
예제 #32
0
 public int Compare(T x, T y)
 {
     return(SafeNativeMethods.StrCmpLogicalW(KeySelector(x), KeySelector(y)));
 }
예제 #33
0
 protected override bool ReleaseHandle()
 {
     return(SafeNativeMethods.FindClose(base.handle));
 }
예제 #34
0
 public static bool CloseHandle(IntPtr handle)
 {
     return(SafeNativeMethods.CloseHandle(handle));
 }
예제 #35
0
        public void Sit(PhysicsActor actor, Vector3 avPos, Vector3 avCameraPosition, Vector3 offset, Vector3 avOffset, SitAvatarCallback PhysicsSitResponse)
        {
            if (!m_scene.haveActor(actor) || !(actor is OdePrim) || ((OdePrim)actor).prim_geom == IntPtr.Zero)
            {
                PhysicsSitResponse(-1, actor.LocalID, offset, Quaternion.Identity);
                return;
            }

            IntPtr geom = ((OdePrim)actor).prim_geom;

            Vector3    geopos  = SafeNativeMethods.GeomGetPositionOMV(geom);
            Quaternion geomOri = SafeNativeMethods.GeomGetQuaternionOMV(geom);

//            Vector3 geopos = actor.Position;
//            Quaternion geomOri = actor.Orientation;

            Quaternion geomInvOri = Quaternion.Conjugate(geomOri);

            Quaternion ori = Quaternion.Identity;

            Vector3 rayDir = geopos + offset - avCameraPosition;

            float raylen = rayDir.Length();

            if (raylen < 0.001f)
            {
                PhysicsSitResponse(-1, actor.LocalID, offset, Quaternion.Identity);
                return;
            }
            float t = 1 / raylen;

            rayDir.X *= t;
            rayDir.Y *= t;
            rayDir.Z *= t;

            raylen += 30f; // focal point may be far
            List <ContactResult> rayResults;

            rayResults = m_scene.RaycastActor(actor, avCameraPosition, rayDir, raylen, 1, RaySitFlags);
            if (rayResults.Count == 0)
            {
/* if this fundamental ray failed, then just fail so user can try another spot and not be sitted far on a big prim
 *              d.AABB aabb;
 *              d.GeomGetAABB(geom, out aabb);
 *              offset = new Vector3(avOffset.X, 0, aabb.MaxZ + avOffset.Z - geopos.Z);
 *              ori = geomInvOri;
 *              offset *= geomInvOri;
 *              PhysicsSitResponse(1, actor.LocalID, offset, ori);
 */
                PhysicsSitResponse(0, actor.LocalID, offset, ori);
                return;
            }

            int status = 1;

            offset = rayResults[0].Pos - geopos;

            SafeNativeMethods.GeomClassID geoclass = SafeNativeMethods.GeomGetClass(geom);

            if (geoclass == SafeNativeMethods.GeomClassID.SphereClass)
            {
                float r = SafeNativeMethods.GeomSphereGetRadius(geom);

                offset.Normalize();
                offset *= r;

                RotAroundZ(offset.X, offset.Y, ref ori);

                if (r < 0.4f)
                {
                    offset = new Vector3(0, 0, r);
                }
                else
                {
                    if (offset.Z < 0.4f)
                    {
                        t = offset.Z;
                        float rsq = r * r;

                        t         = 1.0f / (rsq - t * t);
                        offset.X *= t;
                        offset.Y *= t;
                        offset.Z  = 0.4f;
                        t         = rsq - 0.16f;
                        offset.X *= t;
                        offset.Y *= t;
                    }
                    else if (r > 0.8f && offset.Z > 0.8f * r)
                    {
                        status      = 3;
                        avOffset.X  = -avOffset.X;
                        avOffset.Z *= 1.6f;
                    }
                }

                offset += avOffset * ori;

                ori     = geomInvOri * ori;
                offset *= geomInvOri;

                PhysicsSitResponse(status, actor.LocalID, offset, ori);
                return;
            }

            Vector3 norm = rayResults[0].Normal;

            if (norm.Z < -0.4f)
            {
                PhysicsSitResponse(0, actor.LocalID, offset, Quaternion.Identity);
                return;
            }


            float SitNormX = -rayDir.X;
            float SitNormY = -rayDir.Y;

            Vector3 pivot = geopos + offset;

            float   edgeNormalX = norm.X;
            float   edgeNormalY = norm.Y;
            float   edgeDirX    = -rayDir.X;
            float   edgeDirY    = -rayDir.Y;
            Vector3 edgePos     = rayResults[0].Pos;
            float   edgeDist    = float.MaxValue;

            bool foundEdge = false;

            if (norm.Z < 0.5f)
            {
                float rayDist = 4.0f;

                for (int i = 0; i < 6; i++)
                {
                    pivot.X -= 0.01f * norm.X;
                    pivot.Y -= 0.01f * norm.Y;
                    pivot.Z -= 0.01f * norm.Z;

                    rayDir.X = -norm.X * norm.Z;
                    rayDir.Y = -norm.Y * norm.Z;
                    rayDir.Z = 1.0f - norm.Z * norm.Z;
                    rayDir.Normalize();

                    rayResults = m_scene.RaycastActor(actor, pivot, rayDir, rayDist, 1, RayFilterFlags.AllPrims);
                    if (rayResults.Count == 0)
                    {
                        break;
                    }

                    if (Math.Abs(rayResults[0].Normal.Z) < 0.7f)
                    {
                        rayDist -= rayResults[0].Depth;
                        if (rayDist < 0f)
                        {
                            break;
                        }

                        pivot       = rayResults[0].Pos;
                        norm        = rayResults[0].Normal;
                        edgeNormalX = norm.X;
                        edgeNormalY = norm.Y;
                        edgeDirX    = -rayDir.X;
                        edgeDirY    = -rayDir.Y;
                    }
                    else
                    {
                        foundEdge = true;
                        edgePos   = rayResults[0].Pos;
                        break;
                    }
                }

                if (!foundEdge)
                {
                    PhysicsSitResponse(0, actor.LocalID, offset, ori);
                    return;
                }
                avOffset.X *= 0.5f;
            }

            else if (norm.Z > 0.866f)
            {
                float toCamBaseX = avCameraPosition.X - pivot.X;
                float toCamBaseY = avCameraPosition.Y - pivot.Y;
                float toCamX     = toCamBaseX;
                float toCamY     = toCamBaseY;

                for (int j = 0; j < 4; j++)
                {
                    float rayDist     = 1.0f;
                    float curEdgeDist = 0.0f;

                    for (int i = 0; i < 3; i++)
                    {
                        pivot.Z -= 0.01f;
                        rayDir.X = toCamX;
                        rayDir.Y = toCamY;
                        rayDir.Z = (-toCamX * norm.X - toCamY * norm.Y) / norm.Z;
                        rayDir.Normalize();

                        rayResults = m_scene.RaycastActor(actor, pivot, rayDir, rayDist, 1, RayFilterFlags.AllPrims);
                        if (rayResults.Count == 0)
                        {
                            break;
                        }

                        curEdgeDist += rayResults[0].Depth;

                        if (rayResults[0].Normal.Z > 0.5f)
                        {
                            rayDist -= rayResults[0].Depth;
                            if (rayDist < 0f)
                            {
                                break;
                            }

                            pivot = rayResults[0].Pos;
                            norm  = rayResults[0].Normal;
                        }
                        else
                        {
                            foundEdge = true;
                            if (curEdgeDist < edgeDist)
                            {
                                edgeDist    = curEdgeDist;
                                edgeNormalX = rayResults[0].Normal.X;
                                edgeNormalY = rayResults[0].Normal.Y;
                                edgeDirX    = rayDir.X;
                                edgeDirY    = rayDir.Y;
                                edgePos     = rayResults[0].Pos;
                            }
                            break;
                        }
                    }
                    if (foundEdge && edgeDist < 0.2f)
                    {
                        break;
                    }

                    pivot = geopos + offset;

                    switch (j)
                    {
                    case 0:
                        toCamX = -toCamBaseY;
                        toCamY = toCamBaseX;
                        break;

                    case 1:
                        toCamX = toCamBaseY;
                        toCamY = -toCamBaseX;
                        break;

                    case 2:
                        toCamX = -toCamBaseX;
                        toCamY = -toCamBaseY;
                        break;

                    default:
                        break;
                    }
                }

                if (!foundEdge)
                {
                    avOffset.X  = -avOffset.X;
                    avOffset.Z *= 1.6f;

                    RotAroundZ(SitNormX, SitNormY, ref ori);

                    offset += avOffset * ori;

                    ori     = geomInvOri * ori;
                    offset *= geomInvOri;

                    PhysicsSitResponse(3, actor.LocalID, offset, ori);
                    return;
                }
                avOffset.X *= 0.5f;
            }

            SitNormX = edgeNormalX;
            SitNormY = edgeNormalY;
            if (edgeDirX * SitNormX + edgeDirY * SitNormY < 0)
            {
                SitNormX = -SitNormX;
                SitNormY = -SitNormY;
            }

            RotAroundZ(SitNormX, SitNormY, ref ori);

            offset  = edgePos + avOffset * ori;
            offset -= geopos;

            ori     = geomInvOri * ori;
            offset *= geomInvOri;

            PhysicsSitResponse(1, actor.LocalID, offset, ori);
            return;
        }
예제 #36
0
        public override bool EditComponent(ITypeDescriptorContext context, object obj, IWin32Window parent)
        {
            IntPtr handle = (parent == null ? IntPtr.Zero : parent.Handle);

            // try to get the page guid
            if (obj is NativeMethods.IPerPropertyBrowsing)
            {
                // check for a property page
                Guid guid = Guid.Empty;
                int  hr   = ((NativeMethods.IPerPropertyBrowsing)obj).MapPropertyToPage(NativeMethods.MEMBERID_NIL, out guid);
                if (hr == NativeMethods.S_OK)
                {
                    if (!guid.Equals(Guid.Empty))
                    {
                        object o = obj;
                        SafeNativeMethods.OleCreatePropertyFrame(new HandleRef(parent, handle), 0, 0, "PropertyPages", 1, ref o, 1, new Guid[] { guid }, Application.CurrentCulture.LCID, 0, IntPtr.Zero);
                        return(true);
                    }
                }
            }

            if (obj is NativeMethods.ISpecifyPropertyPages)
            {
                try {
                    NativeMethods.tagCAUUID uuids = new NativeMethods.tagCAUUID();
                    try {
                        ((NativeMethods.ISpecifyPropertyPages)obj).GetPages(uuids);
                        if (uuids.cElems <= 0)
                        {
                            return(false);
                        }
                    }
                    catch (Exception) {
                        return(false);
                    }
                    try {
                        object o = obj;
                        SafeNativeMethods.OleCreatePropertyFrame(new HandleRef(parent, handle), 0, 0, "PropertyPages", 1, ref o, uuids.cElems, new HandleRef(uuids, uuids.pElems), Application.CurrentCulture.LCID, 0, IntPtr.Zero);
                        return(true);
                    }
                    finally {
                        if (uuids.pElems != IntPtr.Zero)
                        {
                            Marshal.FreeCoTaskMem(uuids.pElems);
                        }
                    }
                }
                catch (Exception ex1) {
                    IUIService uiSvc = null;

                    if (context != null)
                    {
                        uiSvc = (IUIService)context.GetService(typeof(IUIService));
                    }

                    String errString = SR.GetString(SR.ErrorPropertyPageFailed);
                    if (uiSvc != null)
                    {
                        uiSvc.ShowError(ex1, errString);
                    }
                    else
                    {
                        MessageBox.Show(errString, "PropertyGrid");
                    }
                }
            }
            return(false);
        }
예제 #37
0
 /// <summary>
 /// ini寫值
 /// </summary>
 /// <param name="Section">集合</param>
 /// <param name="Key">索引</param>
 /// <param name="Value">值</param>
 /// <param name="inipath">ini路徑</param>
 public void IniWriteValue(string Section, string Key, string Value, string inipath)
 {
     SafeNativeMethods.WritePrivateProfileString(Section, Key, Value, Path.Combine(App.Root, inipath));
 }
예제 #38
0
 public static extern bool CreateProcessAsUser(SafeHandle hToken, string lpApplicationName, string lpCommandLine, NativeMethods.SECURITY_ATTRIBUTES lpProcessAttributes, NativeMethods.SECURITY_ATTRIBUTES lpThreadAttributes, bool bInheritHandles, int dwCreationFlags, HandleRef lpEnvironment, string lpCurrentDirectory, NativeMethods.STARTUPINFO lpStartupInfo, SafeNativeMethods.PROCESS_INFORMATION lpProcessInformation);
예제 #39
0
        private static unsafe void GetRegionScans(IntPtr hRgn, out Rectangle[] scans)
        {
            uint bytes     = 0;
            int  countdown = 100;
            int  error     = 0;

            // HACK: It seems that sometimes the GetRegionData will return ERROR_INVALID_HANDLE
            //       even though the handle (the HRGN) is fine. Maybe the function is not
            //       re-entrant? I'm not sure, but trying it again seems to fix it.
            while (countdown > 0)
            {
                bytes = SafeNativeMethods.GetRegionData(hRgn, 0, (NativeStructs.RGNDATA *)IntPtr.Zero);
                error = Marshal.GetLastWin32Error();

                if (bytes == 0)
                {
                    --countdown;
                    System.Threading.Thread.Sleep(5);
                }
                else
                {
                    break;
                }
            }

            // But if we retry several times and it still messes up then we will finally give up.
            if (bytes == 0)
            {
                throw new Win32Exception(error, "GetRegionData returned " + bytes.ToString(CultureInfo.CurrentCulture) + ", GetLastError() = " + error.ToString(CultureInfo.CurrentCulture));
            }

            byte *data;

            // Up to 512 bytes, allocate on the stack. Otherwise allocate from the heap.
            if (bytes <= 512)
            {
                byte *data1 = stackalloc byte[(int)bytes];
                data = data1;
            }
            else
            {
                data = (byte *)Memory.Allocate(bytes, false).ToPointer();
            }

            try
            {
                NativeStructs.RGNDATA *pRgnData = (NativeStructs.RGNDATA *)data;
                uint result = SafeNativeMethods.GetRegionData(hRgn, bytes, pRgnData);

                if (result != bytes)
                {
                    throw new OutOfMemoryException("SafeNativeMethods.GetRegionData returned 0");
                }

                NativeStructs.RECT *pRects = NativeStructs.RGNDATA.GetRectsPointer(pRgnData);
                scans = new Rectangle[pRgnData->rdh.nCount];

                for (int i = 0; i < scans.Length; ++i)
                {
                    scans[i] = Rectangle.FromLTRB(pRects[i].left, pRects[i].top, pRects[i].right, pRects[i].bottom);
                }

                pRects   = null;
                pRgnData = null;
            }
            finally
            {
                if (bytes > 512)
                {
                    Memory.Free(new IntPtr(data));
                }
            }
        }
예제 #40
0
 private PaperSize PaperSizeFromMode(SafeNativeMethods.DEVMODE mode) {
     PaperSize[] sizes = printerSettings.Get_PaperSizes();
     if ((mode.dmFields & SafeNativeMethods.DM_PAPERSIZE) == SafeNativeMethods.DM_PAPERSIZE)
     {
         for (int i = 0; i < sizes.Length; i++) {
             if ((int)sizes[i].RawKind == mode.dmPaperSize)
                 return sizes[i];
         }
     }
     return new PaperSize(PaperKind.Custom, "custom",
                              //mode.dmPaperWidth, mode.dmPaperLength);
                              PrinterUnitConvert.Convert(mode.dmPaperWidth, PrinterUnit.TenthsOfAMillimeter, PrinterUnit.Display),
                              PrinterUnitConvert.Convert(mode.dmPaperLength, PrinterUnit.TenthsOfAMillimeter, PrinterUnit.Display));
 }
 public int Compare(string a, string b)
 {
     return(SafeNativeMethods.StrCmpLogicalW(a, b));
 }
예제 #42
0
 private PrinterResolution PrinterResolutionFromMode(SafeNativeMethods.DEVMODE mode) {
     PrinterResolution[] resolutions = printerSettings.Get_PrinterResolutions();
     for (int i = 0; i < resolutions.Length; i++) {
         if (mode.dmPrintQuality >= 0 && ((mode.dmFields & SafeNativeMethods.DM_PRINTQUALITY) == SafeNativeMethods.DM_PRINTQUALITY)
             && ((mode.dmFields & SafeNativeMethods.DM_YRESOLUTION) == SafeNativeMethods.DM_YRESOLUTION)) {
             if (resolutions[i].X == unchecked((int)(PrinterResolutionKind) mode.dmPrintQuality)
                 && resolutions[i].Y == unchecked((int)(PrinterResolutionKind) mode.dmYResolution))
                 return resolutions[i];
         }
         else {
             if ((mode.dmFields & SafeNativeMethods.DM_PRINTQUALITY) == SafeNativeMethods.DM_PRINTQUALITY)
             {
                 if (resolutions[i].Kind == (PrinterResolutionKind) mode.dmPrintQuality)
                     return resolutions[i];
             }
         }
     }
     return new PrinterResolution(PrinterResolutionKind.Custom,
                                  mode.dmPrintQuality, mode.dmYResolution);
 }
예제 #43
0
        public static void Init()
        {
            int status = SafeNativeMethods.xnLogInitSystem();

            WrapperUtils.ThrowOnError(status);
        }
예제 #44
0
        private static void ImportPathElement(IntPtr info, ref SafeNativeMethods.CGPathElement element)
        {
            var handle = GCHandle.FromIntPtr(info);
            var @this = handle.Target as PathData;
            int pointCount;

            @this.commandList.Add(element.type);

            switch ((int)element.type)
            {
                case (int)PathCommand.MoveTo:
                case (int)PathCommand.LineTo:
                    pointCount = 1;
                    break;
                case (int)PathCommand.QuaddraticCurveTo: pointCount = 2; break;
                case (int)PathCommand.CubicCurveTo: pointCount = 3; break;
                default: return;
            }

            if (ObjectiveC.LP64) @this.AppendPointList(element.points, pointCount);
            else @this.ApendPointFList(element.points, pointCount);
        }
예제 #45
0
파일: Gdiplus.cs 프로젝트: JianwenSun/cc
 public static int GetObject(HandleRef hObject, SafeNativeMethods.LOGFONT lp) {
     return GetObject(hObject, System.Runtime.InteropServices.Marshal.SizeOf(typeof(SafeNativeMethods.LOGFONT)), lp);
 }