Cursor Classe

Definizione

Rappresenta l'immagine usata per disegnare il puntatore del mouse.

public ref class Cursor sealed : IDisposable, System::Runtime::Serialization::ISerializable
[System.ComponentModel.TypeConverter(typeof(System.Windows.Forms.CursorConverter))]
[System.Serializable]
public sealed class Cursor : IDisposable, System.Runtime.Serialization.ISerializable
[System.ComponentModel.TypeConverter(typeof(System.Windows.Forms.CursorConverter))]
public sealed class Cursor : IDisposable, System.Runtime.Serialization.ISerializable
[<System.ComponentModel.TypeConverter(typeof(System.Windows.Forms.CursorConverter))>]
[<System.Serializable>]
type Cursor = class
    interface IDisposable
    interface ISerializable
[<System.ComponentModel.TypeConverter(typeof(System.Windows.Forms.CursorConverter))>]
type Cursor = class
    interface IDisposable
    interface ISerializable
Public NotInheritable Class Cursor
Implements IDisposable, ISerializable
Ereditarietà
Cursor
Attributi
Implementazioni

Esempio

Nell'esempio di codice seguente viene visualizzato un modulo che illustra l'uso di un cursore personalizzato. Il personalizzato Cursor è incorporato nel file di risorse dell'applicazione. L'esempio richiede un cursore contenuto in un file di cursore denominato MyCursor.cur. Per compilare questo esempio usando la riga di comando, includere il flag seguente: /res:MyCursor.Cur, CustomCursor.MyCursor.Cur

using System;
using System.Drawing;
using System.Windows.Forms;

namespace CustomCursor
{
    public class Form1 : System.Windows.Forms.Form
    {
        [STAThread]
        static void Main() 
        {
            Application.Run(new Form1());
        }

        public Form1()
        {
            this.ClientSize = new System.Drawing.Size(292, 266);
            this.Text = "Cursor Example";
            
            // The following generates a cursor from an embedded resource.
            
            // To add a custom cursor, create a bitmap
            //        1. Add a new cursor file to your project: 
            //                Project->Add New Item->General->Cursor File

            // --- To make the custom cursor an embedded resource  ---
            
            // In Visual Studio:
            //        1. Select the cursor file in the Solution Explorer
            //        2. Choose View->Properties.
            //        3. In the properties window switch "Build Action" to "Embedded Resources"

            // On the command line:
            //        Add the following flag:
            //            /res:CursorFileName.cur,Namespace.CursorFileName.cur
            //        
            //        Where "Namespace" is the namespace in which you want to use the cursor
            //        and   "CursorFileName.cur" is the cursor filename.

            // The following line uses the namespace from the passed-in type
            // and looks for CustomCursor.MyCursor.Cur in the assemblies manifest.
        // NOTE: The cursor name is acase sensitive.
            this.Cursor = new Cursor(GetType(), "MyCursor.cur");  
        }
    }
}
Imports System.Drawing
Imports System.Windows.Forms

Namespace CustomCursor
   
   Public Class Form1
      Inherits System.Windows.Forms.Form
      
      <System.STAThread()> _
      Public Shared Sub Main()
         System.Windows.Forms.Application.Run(New Form1())
      End Sub

      Public Sub New()

         Me.ClientSize = New System.Drawing.Size(292, 266)
         Me.Text = "Cursor Example"
         
        ' The following generates a cursor from an embedded resource.
         
        'To add a custom cursor, create a bitmap
        '       1. Add a new cursor file to your project: 
        '               Project->Add New Item->General->Cursor File

        '--- To make the custom cursor an embedded resource  ---

        'In Visual Studio:
        '       1. Select the cursor file in the Solution Explorer
        '       2. Choose View->Properties.
        '       3. In the properties window switch "Build Action" to "Embedded Resources"

        'On the command line:
        '       Add the following flag:
        '           /res:CursorFileName.cur,Namespace.CursorFileName.cur

        '       Where "Namespace" is the namespace in which you want to use the cursor
        '       and   "CursorFileName.cur" is the cursor filename.

        'The following line uses the namespace from the passed-in type
        'and looks for CustomCursor.MyCursor.cur in the assemblies manifest.
        'NOTE: The cursor name is acase sensitive.
        Me.Cursor = New Cursor(Me.GetType(), "MyCursor.cur")
      End Sub
   End Class
End Namespace 'CustomCursor

Nell'esempio di codice seguente vengono visualizzate le informazioni sui clienti in un TreeView controllo. I nodi dell'albero radice visualizzano i nomi dei clienti e i nodi dell'albero figlio visualizzano i numeri di ordine assegnati a ogni cliente. In questo esempio vengono visualizzati 1.000 clienti con 15 ordini. Il ripainting dell'oggetto TreeView viene eliminato usando i BeginUpdate metodi e EndUpdate e viene visualizzata un'attesa Cursor mentre TreeView crea e disegna gli TreeNode oggetti. In questo esempio è necessario disporre di un file di cursore denominato MyWait.cur nella directory dell'applicazione. Richiede anche un Customer oggetto che può contenere una raccolta di Order oggetti e che è stata creata un'istanza di un TreeView controllo in un Formoggetto .

// The basic Customer class.
ref class Customer: public System::Object
{
private:
   String^ custName;

protected:
   ArrayList^ custOrders;

public:
   Customer( String^ customername )
   {
      custName = "";
      custOrders = gcnew ArrayList;
      this->custName = customername;
   }


   property String^ CustomerName 
   {
      String^ get()
      {
         return this->custName;
      }

      void set( String^ value )
      {
         this->custName = value;
      }

   }

   property ArrayList^ CustomerOrders 
   {
      ArrayList^ get()
      {
         return this->custOrders;
      }

   }

};


// End Customer class
// The basic customer Order class.
ref class Order: public System::Object
{
private:
   String^ ordID;

public:
   Order( String^ orderid )
   {
      ordID = "";
      this->ordID = orderid;
   }


   property String^ OrderID 
   {
      String^ get()
      {
         return this->ordID;
      }

      void set( String^ value )
      {
         this->ordID = value;
      }

   }

};
// End Order class



void FillMyTreeView()
{
   // Add customers to the ArrayList of Customer objects.
   for ( int x = 0; x < 1000; x++ )
   {
      customerArray->Add( gcnew Customer( "Customer " + x ) );
   }
   
   // Add orders to each Customer object in the ArrayList.
   IEnumerator^ myEnum = customerArray->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      Customer^ customer1 = safe_cast<Customer^>(myEnum->Current);
      for ( int y = 0; y < 15; y++ )
      {
         customer1->CustomerOrders->Add( gcnew Order( "Order " + y ) );
      }
   }

   // Display a wait cursor while the TreeNodes are being created.
   ::Cursor::Current = gcnew System::Windows::Forms::Cursor( "MyWait.cur" );
   
   // Suppress repainting the TreeView until all the objects have been created.
   treeView1->BeginUpdate();
   
   // Clear the TreeView each time the method is called.
   treeView1->Nodes->Clear();
   
   // Add a root TreeNode for each Customer object in the ArrayList.
   myEnum = customerArray->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      Customer^ customer2 = safe_cast<Customer^>(myEnum->Current);
      treeView1->Nodes->Add( gcnew TreeNode( customer2->CustomerName ) );
      
      // Add a child treenode for each Order object in the current Customer object.
      IEnumerator^ myEnum = customer2->CustomerOrders->GetEnumerator();
      while ( myEnum->MoveNext() )
      {
         Order^ order1 = safe_cast<Order^>(myEnum->Current);
         treeView1->Nodes[ customerArray->IndexOf( customer2 ) ]->Nodes->Add( gcnew TreeNode( customer2->CustomerName + "." + order1->OrderID ) );
      }
   }
   
   // Reset the cursor to the default for all controls.
   ::Cursor::Current = Cursors::Default;
   
   // Begin repainting the TreeView.
   treeView1->EndUpdate();
}

// The basic Customer class.
public class Customer : System.Object
{
   private string custName = "";
   protected ArrayList custOrders = new ArrayList();

   public Customer(string customername)
   {
      this.custName = customername;
   }

   public string CustomerName
   {      
      get{return this.custName;}
      set{this.custName = value;}
   }

   public ArrayList CustomerOrders 
   {
      get{return this.custOrders;}
   }
} // End Customer class 

// The basic customer Order class.
public class Order : System.Object
{
   private string ordID = "";

   public Order(string orderid)
   {
      this.ordID = orderid;
   }

   public string OrderID
   {      
      get{return this.ordID;}
      set{this.ordID = value;}
   }
} // End Order class

// Create a new ArrayList to hold the Customer objects.
private ArrayList customerArray = new ArrayList(); 

private void FillMyTreeView()
{
   // Add customers to the ArrayList of Customer objects.
   for(int x=0; x<1000; x++)
   {
      customerArray.Add(new Customer("Customer" + x.ToString()));
   }

   // Add orders to each Customer object in the ArrayList.
   foreach(Customer customer1 in customerArray)
   {
      for(int y=0; y<15; y++)
      {
         customer1.CustomerOrders.Add(new Order("Order" + y.ToString()));    
      }
   }

   // Display a wait cursor while the TreeNodes are being created.
   Cursor.Current = new Cursor("MyWait.cur");
        
   // Suppress repainting the TreeView until all the objects have been created.
   treeView1.BeginUpdate();

   // Clear the TreeView each time the method is called.
   treeView1.Nodes.Clear();

   // Add a root TreeNode for each Customer object in the ArrayList.
   foreach(Customer customer2 in customerArray)
   {
      treeView1.Nodes.Add(new TreeNode(customer2.CustomerName));
          
      // Add a child treenode for each Order object in the current Customer object.
      foreach(Order order1 in customer2.CustomerOrders)
      {
         treeView1.Nodes[customerArray.IndexOf(customer2)].Nodes.Add(
           new TreeNode(customer2.CustomerName + "." + order1.OrderID));
      }
   }

   // Reset the cursor to the default for all controls.
   Cursor.Current = Cursors.Default;

   // Begin repainting the TreeView.
   treeView1.EndUpdate();
}
Public Class Customer
   Inherits [Object]
   Private custName As String = ""
   Friend custOrders As New ArrayList()

   Public Sub New(ByVal customername As String)
      Me.custName = customername
   End Sub

   Public Property CustomerName() As String
      Get
         Return Me.custName
      End Get
      Set(ByVal Value As String)
         Me.custName = Value
      End Set
   End Property

   Public ReadOnly Property CustomerOrders() As ArrayList
      Get
         Return Me.custOrders
      End Get
   End Property
End Class


Public Class Order
   Inherits [Object]
   Private ordID As String

   Public Sub New(ByVal orderid As String)
      Me.ordID = orderid
   End Sub

   Public Property OrderID() As String
      Get
         Return Me.ordID
      End Get
      Set(ByVal Value As String)
         Me.ordID = Value
      End Set
   End Property
End Class

' Create a new ArrayList to hold the Customer objects.
Private customerArray As New ArrayList()

Private Sub FillMyTreeView()
   ' Add customers to the ArrayList of Customer objects.
   Dim x As Integer
   For x = 0 To 999
      customerArray.Add(New Customer("Customer" + x.ToString()))
   Next x

   ' Add orders to each Customer object in the ArrayList.
   Dim customer1 As Customer
   For Each customer1 In customerArray
      Dim y As Integer
      For y = 0 To 14
         customer1.CustomerOrders.Add(New Order("Order" + y.ToString()))
      Next y
   Next customer1

   ' Display a wait cursor while the TreeNodes are being created.
   Cursor.Current = New Cursor("MyWait.cur")

   ' Suppress repainting the TreeView until all the objects have been created.
   treeView1.BeginUpdate()

   ' Clear the TreeView each time the method is called.
   treeView1.Nodes.Clear()

   ' Add a root TreeNode for each Customer object in the ArrayList.
   Dim customer2 As Customer
   For Each customer2 In customerArray
      treeView1.Nodes.Add(New TreeNode(customer2.CustomerName))

      ' Add a child TreeNode for each Order object in the current Customer object.
      Dim order1 As Order
      For Each order1 In customer2.CustomerOrders
         treeView1.Nodes(customerArray.IndexOf(customer2)).Nodes.Add( _
    New TreeNode(customer2.CustomerName + "." + order1.OrderID))
      Next order1
   Next customer2

   ' Reset the cursor to the default for all controls.
   Cursor.Current = System.Windows.Forms.Cursors.Default

   ' Begin repainting the TreeView.
   treeView1.EndUpdate()
End Sub

Commenti

Un cursore è una piccola immagine la cui posizione sullo schermo è controllata da un dispositivo di puntamento, ad esempio un mouse, una penna o un trackball. Quando l'utente sposta il dispositivo di puntamento, il sistema operativo sposta di conseguenza il cursore.

Vengono usate forme di cursore diverse per informare l'utente che operazione avrà il mouse. Ad esempio, quando si modifica o si seleziona testo, viene in genere visualizzato un Cursors.IBeam cursore. Un cursore di attesa viene comunemente usato per informare l'utente che un processo è attualmente in esecuzione. Esempi di processi che potrebbero essere in attesa dell'apertura di un file, salvataggio di un file o riempimento di un controllo, ad esempio , DataGridListBox o TreeView con una grande quantità di dati.

Tutti i controlli che derivano dalla Control classe hanno una Cursor proprietà. Per modificare il cursore visualizzato dal puntatore del mouse quando si trova all'interno dei limiti del controllo, assegnare un Cursor oggetto alla Cursor proprietà del controllo. In alternativa, è possibile visualizzare i cursori a livello di applicazione assegnando un oggetto Cursor alla Current proprietà. Ad esempio, se lo scopo dell'applicazione è modificare un file di testo, è possibile impostare la Current proprietà su per Cursors.WaitCursor visualizzare un cursore di attesa sull'applicazione mentre il file carica o salva per impedire l'elaborazione di eventuali eventi del mouse. Al termine del processo, impostare la Current proprietà su Cursors.Default per l'applicazione per visualizzare il cursore appropriato su ogni tipo di controllo.

Nota

Se si chiama Application.DoEvents prima di reimpostare la Current proprietà Cursors.Default al cursore, l'applicazione riprenderà l'ascolto degli eventi del mouse e riprenderà a visualizzare il controllo appropriato Cursor per ogni controllo nell'applicazione.

Gli oggetti cursori possono essere creati da diverse origini, ad esempio l'handle di un file esistente Cursor, un file standard Cursor , una risorsa o un flusso di dati.

Nota

La Cursor classe non supporta cursori animati (file con estensione ani) o cursori con colori diversi da nero e bianco.

Se l'immagine usata come cursore è troppo piccola, è possibile usare il DrawStretched metodo per forzare l'immagine per riempire i limiti del cursore. È possibile nascondere temporaneamente il cursore chiamando il Hide metodo e ripristinandolo chiamando il Show metodo.

A partire da .NET Framework 4.5.2, verrà Cursor ridimensionato in base all'impostazione DPI di sistema quando il file app.config contiene la voce seguente:

<appSettings>  
  <add key="EnableWindowsFormsHighDpiAutoResizing" value="true" />  
</appSettings>  

Costruttori

Cursor(IntPtr)

Inizializza una nuova istanza della classe Cursor dal punto di controllo di Windows specificato.

Cursor(Stream)

Inizializza una nuova istanza della classe Cursor dal flusso dei dati specificato.

Cursor(String)

Inizializza una nuova istanza della classe Cursor dal file specificato.

Cursor(Type, String)

Inizializza una nuova istanza della classe Cursor dalla risorsa specificata con il tipo di risorsa definito.

Proprietà

Clip

Ottiene o imposta i limiti che rappresentano il rettangolo di ridimensionamento per il cursore.

Current

Ottiene o imposta l'oggetto cursore che rappresenta il cursore del mouse.

Handle

Ottiene il punto di controllo del cursore.

HotSpot

Ottiene l'area sensibile di un cursore.

Position

Ottiene o imposta la posizione del cursore.

Size

Ottiene la dimensione dell'oggetto cursore.

Tag

Ottiene o imposta l'oggetto che contiene i dati relativi all'oggetto Cursor.

Metodi

CopyHandle()

Copia l'handle di questo oggetto Cursor.

Dispose()

Rilascia tutte le risorse usate da Cursor.

Draw(Graphics, Rectangle)

Disegna il cursore sulla superficie specificata e all'interno dei limiti definiti.

DrawStretched(Graphics, Rectangle)

Disegna il cursore in formato ingrandito sulla superficie specificata e all'interno dei limiti definiti.

Equals(Object)

Restituisce un valore che indica se il cursore è uguale all'oggetto Cursor specificato.

Finalize()

Consente a un oggetto di effettuare un tentativo di liberare risorse ed eseguire altre operazioni di pulizia prima che venga recuperato da Garbage Collection.

GetHashCode()

Recupera il codice hash per l'oggetto Cursor corrente.

GetType()

Ottiene l'oggetto Type dell'istanza corrente.

(Ereditato da Object)
Hide()

Nasconde il cursore.

MemberwiseClone()

Crea una copia superficiale dell'oggetto Object corrente.

(Ereditato da Object)
Show()

Visualizza il cursore.

ToString()

Recupera una stringa leggibile che rappresenta questo oggetto Cursor.

Operatori

Equality(Cursor, Cursor)

Restituisce un valore che indica se due istanze di una classe Cursor sono uguali.

Inequality(Cursor, Cursor)

Restituisce un valore che indica se due istanze di Cursor non sono uguali.

Implementazioni dell'interfaccia esplicita

ISerializable.GetObjectData(SerializationInfo, StreamingContext)

Serializza l'oggetto.

Si applica a

Vedi anche