Este tema aún no ha recibido ninguna valoración - Valorar este tema

Cursor (Clase)

Actualización: noviembre 2007

Representa la imagen que se utiliza para dibujar el puntero del mouse (ratón).

Espacio de nombres:  System.Windows.Forms
Ensamblado:  System.Windows.Forms (en System.Windows.Forms.dll)
[SerializableAttribute]
[TypeConverterAttribute(typeof(CursorConverter))]
public sealed class Cursor : IDisposable, 
	ISerializable
/** @attribute SerializableAttribute */ 
/** @attribute TypeConverterAttribute(CursorConverter) */
public final class Cursor implements IDisposable, 
	ISerializable
public final class Cursor implements IDisposable, ISerializable

Un cursor es una pequeña imagen cuya ubicación en pantalla se controla mediante un dispositivo señalador, como un mouse, un lápiz o una bola de seguimiento. Cuando el usuario desplaza el dispositivo señalador, el sistema operativo mueve el cursor de la manera adecuada.

Para informar al usuario de la operación que realizará el mouse, se utilizan distintas formas de cursor. Por ejemplo, al editar o seleccionar texto, suele mostrarse un cursor Cursors.IBeam. Para informar al usuario de que se está ejecutando un proceso, se utiliza un cursor de espera. Abrir un archivo, guardar un archivo o llenar un control como DataGrid, ListBox o TreeView con una gran cantidad de datos son algunos ejemplos de procesos en los que el usuario debe esperar.

Todos los controles que se derivan de la clase Control tienen una propiedad Cursor. Para cambiar el cursor que muestra el puntero del mouse cuando está dentro de los límites del control, asigne Cursor a la propiedad Cursor del control. Alternativamente, puede mostrar cursores en el nivel de aplicación al asignar Cursor a la propiedad Current. Por ejemplo, si el objetivo de la aplicación es editar un archivo de texto, puede establecer la propiedad Current en Cursors.WaitCursor para que se muestre un cursor de espera sobre la aplicación mientras el archivo se carga o se guarda, con el fin de impedir que se procesen eventos de mouse. Cuando el proceso finalice, establezca la propiedad Current en Cursors.Default para que la aplicación muestre el cursor adecuado encima de cada tipo de control.

sf27z138.alert_note(es-es,VS.90).gif Nota:

Si llama a Application.DoEvents antes de restablecer la propiedad Current de nuevo en el cursor Cursors.Default, la aplicación reanudará la escucha de eventos de mouse y la presentación del Cursor adecuado para cada control de la aplicación.

Los objetos cursor se pueden crear a partir de varios orígenes, como el identificador de un objeto Cursor existente, un archivo Cursor estándar, un recurso o una secuencia de datos.

sf27z138.alert_note(es-es,VS.90).gif Nota:

La clase Cursor no admite cursores animados (archivos .ani) ni cursores con colores distintos al blanco y negro.

Si la imagen que se utiliza como cursor es demasiado pequeña, puede llamar al método DrawStretched para hacer que la imagen llene los límites del cursor. Para ocultar el cursor temporalmente, llame al método Hide y, para restaurarlo, llame al método Show.

El ejemplo de código siguiente muestra un formulario que muestra cómo utilizar un cursor personalizado. El Cursor personalizado se incrusta en el archivo de recursos de la aplicación. En el ejemplo se requiere un cursor incluido en un archivo de cursor denominado MyCursor.cur. Para compilar este ejemplo utilizando la línea de comandos, hay que incluir el siguiente indicador: /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 or use an existing 16x16 bitmap
            //        1. Add a new cursor file to your project: 
            //                File->Add New Item->Local Project Items->Cursor File
            //        2. Select 16x16 image type:
            //                Image->Current Icon Image Types->16x16

            // --- 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"

            // 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");  

        }
    }
}


package CustomCursor;

import System.*;
import System.Drawing.*;
import System.Windows.Forms.*;

public class Form1 extends System.Windows.Forms.Form
{
    /** @attribute STAThread()
     */
    public static void main(String[] args)
    {
        Application.Run(new Form1());
    } //main

    public Form1()
    {
        this.set_ClientSize(new System.Drawing.Size(292, 266));
        this.set_Text("Cursor Example");
        // The following generates a cursor from an embedded resource.
        // To add a custom cursor, create or use an existing 16x16 bitmap
        //        1. Add a new cursor file to your project: 
        //                File->Add New Item->Local Project Items->Cursor File
        //        2. Select 16x16 image type:
        //                Image->Current Icon Image Types->16x16
        // --- 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"
        // 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.set_Cursor(new Cursor(GetType(), "MyCursor.Cur"));
    } //Form1 
} //Form1


En el ejemplo de código siguiente, se muestra la información de los clientes en un control TreeView. Los nodos del árbol raíz muestran los nombres de los clientes y los nodos secundarios muestran los números de pedido asignados a cada cliente. En este ejemplo, se muestran 1.000 clientes con 15 pedidos cada uno. Para impedir que TreeView vuelva a dibujarse, se utilizan los métodos BeginUpdate y EndUpdate, y se muestra un Cursor de espera mientras TreeView crea y dibuja los objetos TreeNode. En este ejemplo, se requiere que se disponga de un archivo de cursor denominado MyWait.cur en el directorio de la aplicación. También se requiere que se disponga de un objeto Customer que pueda almacenar una colección de objetos Order y que se haya creado una instancia de un control TreeView en Form.


// 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();
}



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

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

    /** @property 
     */
    public String get_CustomerName()
    {
        return this.custName;
    } //get_CustomerName

    /** @property 
     */
    public void set_CustomerName(String value)
    {
        this.custName = value;
    } //set_CustomerName

    /** @property 
     */
    public ArrayList get_CustomerOrders()
    {
        return this.custOrders;
    } //get_CustomerOrders
} //End Customer class

// The basic customer Order class.
public class Order extends Object
{
    private String ordID = "";

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

    /** @property 
     */
    public String get_OrderID()
    {
        return this.ordID;
    } //get_OrderID

    /** @property 
     */
    public void set_OrderID(String value)
    {
        this.ordID = value;
    } //set_OrderID
} // 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"
            + ((Int32)x).ToString()));
    }
    // Add orders to each Customer object in the ArrayList.
    for (int iCtr = 0; iCtr < customerArray.get_Count(); iCtr++) {
        Customer customer1 = (Customer)customerArray.get_Item(iCtr);
        for (int y = 0; y < 15; y++) {
            customer1.get_CustomerOrders().Add(new Order("Order"
                + ((Int32)y).ToString()));
        }
    }
    // Display a wait cursor while the TreeNodes are being created.
    get_Cursor().set_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.get_Nodes().Clear();
    // Add a root TreeNode for each Customer object in the ArrayList.
    for (int iCtr1 = 0; iCtr1 < customerArray.get_Count(); iCtr1++) {
        Customer customer2 = (Customer)customerArray.get_Item(iCtr1);
        treeView1.get_Nodes().Add(new TreeNode(customer2.get_CustomerName()));
        // Add a child treenode for each Order object in the current
        // Customer object.
        for (int iCtr2 = 0; iCtr2 < customer2.get_CustomerOrders().
            get_Count(); iCtr2++) {
            Order order1 = (Order)customer2.get_CustomerOrders().
                get_Item(iCtr2);
            treeView1.get_Nodes().
                get_Item(customerArray.IndexOf(customer2)).get_Nodes().
                Add(new TreeNode(customer2.get_CustomerName() + "."
                + order1.get_OrderID()));
        }
    }
    // Reset the cursor to the default for all controls.
    get_Cursor().set_Current(Cursors.get_Default());
    // Begin repainting the TreeView.
    treeView1.EndUpdate();
} //FillMyTreeView


System.Object
  System.Windows.Forms.Cursor
Todos los miembros static (Shared en Visual Basic) públicos de este tipo son seguros para la ejecución de subprocesos. No se garantiza que los miembros de instancias sean seguros para la ejecución de subprocesos.

Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile para Smartphone, Windows Mobile para Pocket PC

.NET Framework y .NET Compact Framework no admiten todas las versiones de cada plataforma. Para obtener una lista de las versiones compatibles, vea Requisitos de sistema de .NET Framework.

.NET Framework

Compatible con: 3.5, 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Compatible con: 3.5, 2.0, 1.0
¿Le ha resultado útil?
(Caracteres restantes: 1500)
Contenido de la comunidad Agregar