Code:
/ Dotnetfx_Win7_3.5.1 / Dotnetfx_Win7_3.5.1 / 3.5.1 / DEVDIV / depot / DevDiv / releases / Orcas / NetFXw7 / wpf / src / Core / CSharp / System / Windows / Input / Cursor.cs / 1 / Cursor.cs
using System; using System.ComponentModel; using System.Text; using System.Globalization; using MS.Win32; using System.Runtime.InteropServices; using System.Resources; using System.IO; using System.Security; using System.Security.Permissions; using SecurityHelper=MS.Internal.PresentationCore.SecurityHelper; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; using MS.Internal.PresentationCore; // FriendAccessAllowed namespace System.Windows.Input { ////// Cursor class to support default cursor types. /// TBD: Support for cutomized cursor types. /// [TypeConverter(typeof(CursorConverter))] [Localizability(LocalizationCategory.None, Readability = Readability.Unreadable)] public sealed class Cursor : IDisposable { ////// Constructor for Standard Cursors, needn't be public as Stock Cursors /// are exposed in Cursors clas. /// /// internal Cursor(CursorType cursorType) { if (IsValidCursorType(cursorType)) { LoadCursorHelper(cursorType); } else { throw new ArgumentException(SR.Get(SRID.InvalidCursorType, cursorType)); } } ////// Cursor from .ani or .cur file /// /// public Cursor(string cursorFile) { if (cursorFile == null) throw new ArgumentNullException("cursorFile"); if ((cursorFile != String.Empty) && (cursorFile.EndsWith(".cur", StringComparison.OrdinalIgnoreCase) || cursorFile.EndsWith(".ani", StringComparison.OrdinalIgnoreCase))) { LoadFromFile(cursorFile); _fileName = cursorFile; } else { throw new ArgumentException(SR.Get(SRID.Cursor_UnsupportedFormat , cursorFile)); } } ////// Cursor from Stream /// /// public Cursor(Stream cursorStream) { if (cursorStream == null) { throw new ArgumentNullException("cursorStream"); } LoadFromStream(cursorStream); } ////// Cursor from a SafeHandle to an HCURSOR /// /// ////// Critical: This causes the cursor to change and accesses the SetHandleInternalMethod /// TreatAsSafe: This code is safe to expose because in the worst case you change cursor for your app /// [SecurityCritical,SecurityTreatAsSafe] [FriendAccessAllowed] //used by ColumnHeader.GetCursor in PresentationFramework internal Cursor(SafeHandle cursorHandle ) { if (! cursorHandle.IsInvalid ) { this._cursorHandle = cursorHandle ; } } ////// Destructor (IDispose pattern) /// ~Cursor() { Dispose(false); } ////// Cleans up the resources allocated by this object. Once called, the cursor /// object is no longer useful. /// public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ////// Critical: SafeHandle code link demands on dispose. /// TreatAsSafe: Safe to dispose a cursor. /// [SecurityCritical, SecurityTreatAsSafe ] void Dispose(bool disposing) { if ( _cursorHandle != null ) { _cursorHandle.Dispose(); _cursorHandle = null; } } ////// CursorType - Cursor Type Enumeration /// ///internal CursorType CursorType { get { return _cursorType; } } /// /// Handle - HCURSOR Interop /// ///internal SafeHandle Handle { get { if ( _cursorHandle == null ) return new NativeMethods.CursorHandle( ); else return _cursorHandle; } } /// /// FileName - .ani or .cur files are allowed /// ///internal String FileName { get { return _fileName; } } /// /// Critical: calls Win32Exception ctor which LinkDemands /// TreatAsSafe: ok to throw an exception in partial trust /// [SecurityCritical, SecurityTreatAsSafe] private void LoadFromFile(string fileName) { SecurityHelper.DemandFileIOReadPermission(fileName); // Load a Custom Cursor _cursorHandle = UnsafeNativeMethods.LoadImageCursor(IntPtr.Zero, fileName, NativeMethods.IMAGE_CURSOR, 0, 0, NativeMethods.LR_DEFAULTCOLOR | NativeMethods.LR_LOADFROMFILE); int errorCode = Marshal.GetLastWin32Error(); if (_cursorHandle == null || SecurityHelper.SafeHandleIsInvalid(_cursorHandle)) { // Note: chandras 02/02/2005 // Bug # 1016022: LoadImage returns a null handle but does not set // the error condition when icon file is of an incorrect type (e.g., .bmp) // // LoadImage has a bug where it doesn't set the correct error code // when a file is given that is not an ico file. Icon load fails // but win32 error code is still zero (success). Thus, we need to // special case this scenario. // if (errorCode != 0) { if ((errorCode == NativeMethods.ERROR_FILE_NOT_FOUND) || (errorCode == NativeMethods.ERROR_PATH_NOT_FOUND)) { throw new Win32Exception(errorCode, SR.Get(SRID.Cursor_LoadImageFailure, fileName)); } else { throw new Win32Exception(errorCode); } } else { throw new ArgumentException(SR.Get(SRID.Cursor_LoadImageFailure, fileName)); } } } private const int BUFFERSIZE = 4096; // the maximum size of the buffer used for loading from stream private void LoadFromStream(Stream cursorStream) { //Generate a temporal file based on the memory stream. // GetTempFileName requires unrestricted Environment permission // FileIOPermission.Write permission. However, since we don't // know the path of the file to be created we have to give // unrestricted permission here. // GetTempFileName documentation does not mention that it throws // any exception. However, if it does, CLR reverts the assert. string filePath = Path.GetTempFileName(); try { using (BinaryReader reader = new BinaryReader(cursorStream)) { using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Write, FileShare.None)) { // Read the bytes from the stream, up to BUFFERSIZE byte[] cursorData = reader.ReadBytes(BUFFERSIZE); int dataSize; // If the buffer is filled up, then write those bytes out and read more bytes up to BUFFERSIZE for (dataSize = cursorData.Length; dataSize >= BUFFERSIZE; dataSize = reader.Read(cursorData, 0 /*index in array*/, BUFFERSIZE /*bytes to read*/)) { fileStream.Write(cursorData, 0 /*index in array*/, BUFFERSIZE /*bytes to write*/); } // Write any remaining bytes fileStream.Write(cursorData, 0 /*index in array*/, dataSize /*bytes to write*/); } } // This method is called with File Write permission still asserted. // However, this method just reads this file into an icon. _cursorHandle = UnsafeNativeMethods.LoadImageCursor(IntPtr.Zero, filePath, NativeMethods.IMAGE_CURSOR, 0, 0, NativeMethods.LR_DEFAULTCOLOR | NativeMethods.LR_LOADFROMFILE); if (_cursorHandle == null || SecurityHelper.SafeHandleIsInvalid(_cursorHandle)) { throw new ArgumentException(SR.Get(SRID.Cursor_InvalidStream)); } } finally { File.Delete(filePath); } } private void LoadCursorHelper(CursorType cursorType) { if (cursorType != CursorType.None) { // Load a Standard Cursor _cursorHandle = SafeNativeMethods.LoadCursor(new HandleRef(this,IntPtr.Zero), (IntPtr)(CursorTypes[(int)cursorType])); } this._cursorType = cursorType; } ////// String Output /// public override string ToString() { if (_fileName != String.Empty) return _fileName; else { // Get the string representation fo the cursor type enumeration. return Enum.GetName(typeof(CursorType), _cursorType); } } private bool IsValidCursorType(CursorType cursorType) { return ((int)cursorType >= (int)CursorType.None && (int)cursorType <= (int)CursorType.ArrowCD); } private string _fileName = String.Empty; private CursorType _cursorType = CursorType.None; private SafeHandle _cursorHandle; private static readonly int[] CursorTypes = { 0, // None NativeMethods.IDC_NO, NativeMethods.IDC_ARROW, NativeMethods.IDC_APPSTARTING, NativeMethods.IDC_CROSS, NativeMethods.IDC_HELP, NativeMethods.IDC_IBEAM, NativeMethods.IDC_SIZEALL, NativeMethods.IDC_SIZENESW, NativeMethods.IDC_SIZENS, NativeMethods.IDC_SIZENWSE, NativeMethods.IDC_SIZEWE, NativeMethods.IDC_UPARROW, NativeMethods.IDC_WAIT, NativeMethods.IDC_HAND, NativeMethods.IDC_ARROW + 119, // PenCursor NativeMethods.IDC_ARROW + 140, // ScrollNSCursor NativeMethods.IDC_ARROW + 141, // ScrollWECursor NativeMethods.IDC_ARROW + 142, // ScrollAllCursor NativeMethods.IDC_ARROW + 143, // ScrollNCursor NativeMethods.IDC_ARROW + 144, // ScrollSCursor NativeMethods.IDC_ARROW + 145, // ScrollWCursor NativeMethods.IDC_ARROW + 146, // ScrollECursor NativeMethods.IDC_ARROW + 147, // ScrollNWCursor NativeMethods.IDC_ARROW + 148, // ScrollNECursor NativeMethods.IDC_ARROW + 149, // ScrollSWCursor NativeMethods.IDC_ARROW + 150, // ScrollSECursor NativeMethods.IDC_ARROW + 151 // ArrowCDCursor }; } } // File provided for Reference Use Only by Microsoft Corporation (c) 2007. // Copyright (c) Microsoft Corporation. All rights reserved. using System; using System.ComponentModel; using System.Text; using System.Globalization; using MS.Win32; using System.Runtime.InteropServices; using System.Resources; using System.IO; using System.Security; using System.Security.Permissions; using SecurityHelper=MS.Internal.PresentationCore.SecurityHelper; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; using MS.Internal.PresentationCore; // FriendAccessAllowed namespace System.Windows.Input { /// /// Cursor class to support default cursor types. /// TBD: Support for cutomized cursor types. /// [TypeConverter(typeof(CursorConverter))] [Localizability(LocalizationCategory.None, Readability = Readability.Unreadable)] public sealed class Cursor : IDisposable { ////// Constructor for Standard Cursors, needn't be public as Stock Cursors /// are exposed in Cursors clas. /// /// internal Cursor(CursorType cursorType) { if (IsValidCursorType(cursorType)) { LoadCursorHelper(cursorType); } else { throw new ArgumentException(SR.Get(SRID.InvalidCursorType, cursorType)); } } ////// Cursor from .ani or .cur file /// /// public Cursor(string cursorFile) { if (cursorFile == null) throw new ArgumentNullException("cursorFile"); if ((cursorFile != String.Empty) && (cursorFile.EndsWith(".cur", StringComparison.OrdinalIgnoreCase) || cursorFile.EndsWith(".ani", StringComparison.OrdinalIgnoreCase))) { LoadFromFile(cursorFile); _fileName = cursorFile; } else { throw new ArgumentException(SR.Get(SRID.Cursor_UnsupportedFormat , cursorFile)); } } ////// Cursor from Stream /// /// public Cursor(Stream cursorStream) { if (cursorStream == null) { throw new ArgumentNullException("cursorStream"); } LoadFromStream(cursorStream); } ////// Cursor from a SafeHandle to an HCURSOR /// /// ////// Critical: This causes the cursor to change and accesses the SetHandleInternalMethod /// TreatAsSafe: This code is safe to expose because in the worst case you change cursor for your app /// [SecurityCritical,SecurityTreatAsSafe] [FriendAccessAllowed] //used by ColumnHeader.GetCursor in PresentationFramework internal Cursor(SafeHandle cursorHandle ) { if (! cursorHandle.IsInvalid ) { this._cursorHandle = cursorHandle ; } } ////// Destructor (IDispose pattern) /// ~Cursor() { Dispose(false); } ////// Cleans up the resources allocated by this object. Once called, the cursor /// object is no longer useful. /// public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ////// Critical: SafeHandle code link demands on dispose. /// TreatAsSafe: Safe to dispose a cursor. /// [SecurityCritical, SecurityTreatAsSafe ] void Dispose(bool disposing) { if ( _cursorHandle != null ) { _cursorHandle.Dispose(); _cursorHandle = null; } } ////// CursorType - Cursor Type Enumeration /// ///internal CursorType CursorType { get { return _cursorType; } } /// /// Handle - HCURSOR Interop /// ///internal SafeHandle Handle { get { if ( _cursorHandle == null ) return new NativeMethods.CursorHandle( ); else return _cursorHandle; } } /// /// FileName - .ani or .cur files are allowed /// ///internal String FileName { get { return _fileName; } } /// /// Critical: calls Win32Exception ctor which LinkDemands /// TreatAsSafe: ok to throw an exception in partial trust /// [SecurityCritical, SecurityTreatAsSafe] private void LoadFromFile(string fileName) { SecurityHelper.DemandFileIOReadPermission(fileName); // Load a Custom Cursor _cursorHandle = UnsafeNativeMethods.LoadImageCursor(IntPtr.Zero, fileName, NativeMethods.IMAGE_CURSOR, 0, 0, NativeMethods.LR_DEFAULTCOLOR | NativeMethods.LR_LOADFROMFILE); int errorCode = Marshal.GetLastWin32Error(); if (_cursorHandle == null || SecurityHelper.SafeHandleIsInvalid(_cursorHandle)) { // Note: chandras 02/02/2005 // Bug # 1016022: LoadImage returns a null handle but does not set // the error condition when icon file is of an incorrect type (e.g., .bmp) // // LoadImage has a bug where it doesn't set the correct error code // when a file is given that is not an ico file. Icon load fails // but win32 error code is still zero (success). Thus, we need to // special case this scenario. // if (errorCode != 0) { if ((errorCode == NativeMethods.ERROR_FILE_NOT_FOUND) || (errorCode == NativeMethods.ERROR_PATH_NOT_FOUND)) { throw new Win32Exception(errorCode, SR.Get(SRID.Cursor_LoadImageFailure, fileName)); } else { throw new Win32Exception(errorCode); } } else { throw new ArgumentException(SR.Get(SRID.Cursor_LoadImageFailure, fileName)); } } } private const int BUFFERSIZE = 4096; // the maximum size of the buffer used for loading from stream private void LoadFromStream(Stream cursorStream) { //Generate a temporal file based on the memory stream. // GetTempFileName requires unrestricted Environment permission // FileIOPermission.Write permission. However, since we don't // know the path of the file to be created we have to give // unrestricted permission here. // GetTempFileName documentation does not mention that it throws // any exception. However, if it does, CLR reverts the assert. string filePath = Path.GetTempFileName(); try { using (BinaryReader reader = new BinaryReader(cursorStream)) { using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Write, FileShare.None)) { // Read the bytes from the stream, up to BUFFERSIZE byte[] cursorData = reader.ReadBytes(BUFFERSIZE); int dataSize; // If the buffer is filled up, then write those bytes out and read more bytes up to BUFFERSIZE for (dataSize = cursorData.Length; dataSize >= BUFFERSIZE; dataSize = reader.Read(cursorData, 0 /*index in array*/, BUFFERSIZE /*bytes to read*/)) { fileStream.Write(cursorData, 0 /*index in array*/, BUFFERSIZE /*bytes to write*/); } // Write any remaining bytes fileStream.Write(cursorData, 0 /*index in array*/, dataSize /*bytes to write*/); } } // This method is called with File Write permission still asserted. // However, this method just reads this file into an icon. _cursorHandle = UnsafeNativeMethods.LoadImageCursor(IntPtr.Zero, filePath, NativeMethods.IMAGE_CURSOR, 0, 0, NativeMethods.LR_DEFAULTCOLOR | NativeMethods.LR_LOADFROMFILE); if (_cursorHandle == null || SecurityHelper.SafeHandleIsInvalid(_cursorHandle)) { throw new ArgumentException(SR.Get(SRID.Cursor_InvalidStream)); } } finally { File.Delete(filePath); } } private void LoadCursorHelper(CursorType cursorType) { if (cursorType != CursorType.None) { // Load a Standard Cursor _cursorHandle = SafeNativeMethods.LoadCursor(new HandleRef(this,IntPtr.Zero), (IntPtr)(CursorTypes[(int)cursorType])); } this._cursorType = cursorType; } ////// String Output /// public override string ToString() { if (_fileName != String.Empty) return _fileName; else { // Get the string representation fo the cursor type enumeration. return Enum.GetName(typeof(CursorType), _cursorType); } } private bool IsValidCursorType(CursorType cursorType) { return ((int)cursorType >= (int)CursorType.None && (int)cursorType <= (int)CursorType.ArrowCD); } private string _fileName = String.Empty; private CursorType _cursorType = CursorType.None; private SafeHandle _cursorHandle; private static readonly int[] CursorTypes = { 0, // None NativeMethods.IDC_NO, NativeMethods.IDC_ARROW, NativeMethods.IDC_APPSTARTING, NativeMethods.IDC_CROSS, NativeMethods.IDC_HELP, NativeMethods.IDC_IBEAM, NativeMethods.IDC_SIZEALL, NativeMethods.IDC_SIZENESW, NativeMethods.IDC_SIZENS, NativeMethods.IDC_SIZENWSE, NativeMethods.IDC_SIZEWE, NativeMethods.IDC_UPARROW, NativeMethods.IDC_WAIT, NativeMethods.IDC_HAND, NativeMethods.IDC_ARROW + 119, // PenCursor NativeMethods.IDC_ARROW + 140, // ScrollNSCursor NativeMethods.IDC_ARROW + 141, // ScrollWECursor NativeMethods.IDC_ARROW + 142, // ScrollAllCursor NativeMethods.IDC_ARROW + 143, // ScrollNCursor NativeMethods.IDC_ARROW + 144, // ScrollSCursor NativeMethods.IDC_ARROW + 145, // ScrollWCursor NativeMethods.IDC_ARROW + 146, // ScrollECursor NativeMethods.IDC_ARROW + 147, // ScrollNWCursor NativeMethods.IDC_ARROW + 148, // ScrollNECursor NativeMethods.IDC_ARROW + 149, // ScrollSWCursor NativeMethods.IDC_ARROW + 150, // ScrollSECursor NativeMethods.IDC_ARROW + 151 // ArrowCDCursor }; } } // File provided for Reference Use Only by Microsoft Corporation (c) 2007. // Copyright (c) Microsoft Corporation. All rights reserved.
Link Menu
This book is available now!
Buy at Amazon US or
Buy at Amazon UK
- LiteralControl.cs
- QuaternionIndependentAnimationStorage.cs
- CommandTreeTypeHelper.cs
- FileCodeGroup.cs
- AdornerDecorator.cs
- _ChunkParse.cs
- ListViewInsertEventArgs.cs
- PartialCachingControl.cs
- SqlNamer.cs
- LoadedOrUnloadedOperation.cs
- IItemContainerGenerator.cs
- ColumnReorderedEventArgs.cs
- QilReference.cs
- StorageConditionPropertyMapping.cs
- DataGridLength.cs
- AttributeAction.cs
- SchemaCollectionPreprocessor.cs
- DateTimeValueSerializerContext.cs
- WebPartConnectionsCancelEventArgs.cs
- SQLBinary.cs
- Compiler.cs
- DrawingAttributeSerializer.cs
- BufferModeSettings.cs
- ExpandCollapseProviderWrapper.cs
- OleDbInfoMessageEvent.cs
- uribuilder.cs
- LinearGradientBrush.cs
- ByeMessageApril2005.cs
- SHA256CryptoServiceProvider.cs
- WpfKnownType.cs
- GridViewPageEventArgs.cs
- Faults.cs
- X500Name.cs
- BaseParagraph.cs
- SqlDependencyListener.cs
- IUnknownConstantAttribute.cs
- ReservationCollection.cs
- CommandConverter.cs
- DataTableMappingCollection.cs
- DtdParser.cs
- QilTargetType.cs
- HealthMonitoringSection.cs
- DataGridParentRows.cs
- DesignTimeVisibleAttribute.cs
- IImplicitResourceProvider.cs
- HashCoreRequest.cs
- TextBoxAutoCompleteSourceConverter.cs
- TextBlock.cs
- ConnectionConsumerAttribute.cs
- MarkupCompilePass2.cs
- CustomValidator.cs
- SchemaObjectWriter.cs
- XmlUtil.cs
- ApplicationManager.cs
- ListViewItem.cs
- NavigatorOutput.cs
- DataStreams.cs
- StringArrayConverter.cs
- BlurBitmapEffect.cs
- DurableRuntimeValidator.cs
- GuidelineSet.cs
- HttpWebRequestElement.cs
- BinHexDecoder.cs
- RenderOptions.cs
- SqlCharStream.cs
- WebControlParameterProxy.cs
- _BufferOffsetSize.cs
- ConfigurationPropertyCollection.cs
- AnchoredBlock.cs
- PointConverter.cs
- ToolStripItemTextRenderEventArgs.cs
- SubpageParaClient.cs
- VariantWrapper.cs
- Splitter.cs
- UndirectedGraph.cs
- HtmlMeta.cs
- ZipIOZip64EndOfCentralDirectoryBlock.cs
- DbParameterCollectionHelper.cs
- XslException.cs
- DescriptionAttribute.cs
- SoapFormatExtensions.cs
- InvalidOleVariantTypeException.cs
- webproxy.cs
- TrustSection.cs
- TextTreePropertyUndoUnit.cs
- ListViewHitTestInfo.cs
- WindowsFormsHost.cs
- SignatureHelper.cs
- SafeCoTaskMem.cs
- ToolTip.cs
- DataGridViewRowCollection.cs
- StringExpressionSet.cs
- Compiler.cs
- StoragePropertyMapping.cs
- SystemThemeKey.cs
- AcceleratedTokenProviderState.cs
- DuplicateContext.cs
- ProbeDuplexAsyncResult.cs
- WebPartEditVerb.cs
- KeyPressEvent.cs