class Program
{
[StructLayout(LayoutKind.Sequential)]
public struct tagRECT
{
/// LONG->int
public int left;
/// LONG->int
public int top;
/// LONG->int
public int right;
/// LONG->int
public int bottom;
}
/// Return Type: BOOL->int
///lpRect: RECT*
[DllImport("user32.dll", EntryPoint = "ClipCursor")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool ClipCursor([In] IntPtr lpRect);
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
tagRECT rect = new tagRECT() { left = 0, top = 0, right = 1, bottom = 1 };
var p = Marshal.AllocHGlobal(Marshal.SizeOf(rect));
Marshal.StructureToPtr(rect, p, false);
ClipCursor(p);//锁定
ClipCursor(IntPtr.Zero);//解锁
}
}
//如果需要,还可以隐藏指针
调用鼠标对用的接口,设置disable即可,启用则为enable
怎样利用多线程句柄设置鼠标忙碌状态呢?当我们在读取数据的时候,或者处理大量数据的时候可能需要把鼠标设置为忙碌状态,等待返回结果。下面的代码可以帮忙实现这点:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace CursorThread
{
public partial class Form1 : Form
{
public delegate int DoSomethingDelegate(int data);
public Form1()
{
InitializeComponent();
}
static int DoSomething(int data)
{
/// <sumary>
/// Do something in this method
/// </sumary>
Thread.Sleep(300);
return data++;
}
private void button1_Click(object sender, EventArgs e)
{
this.Cursor = Cursors.Default;
DoSomethingDelegate d = DoSomething;
IAsyncResult ar = d.BeginInvoke(100,null, null);
while (true)
{
this.Cursor = Cursors.WaitCursor;
if(ar.AsyncWaitHandle.WaitOne(50, false))
{
this.Cursor = Cursors.Arrow;
break;
}
}
//Get the result
int result = d.EndInvoke(ar);
MessageBox.Show(result.ToString());
}
}
}
这样在点击鼠标后,鼠标会变成忙碌状态一直等待DoSomething这个方法调用结束,然后变回箭头状态。
当然你也可以这样:
// Set the status of the cursor
this.Cursor = Cursor.Busy;
// Do Something
// Set the status of the cursor
this.Cursor = Cursor.Arrow;
--如果是在方法里面调用的话,不能使用this关键字,那你可以这样做:
private void Method()
{
Curosor.Current = Cursor.WaitCursor;
/// Do Something
Cursor.Current = Cursor.Arrow;
}
--在c#程序中,当程序执行某功能时,可以将鼠标设置成忙碌状态。
private void Ddocilck_Click(object sender, EventArgs e)
{
this.Cursor = System.Windows.Forms.Cursors.WaitCursor;//鼠标为忙碌状态
/*
**执行代码**
*/
this.Cursor = System.Windows.Forms.Cursors.Arrow;//设置鼠标为正常状态
}
/**
使用C#改变鼠标的指针形状
1.在一个无标题的窗体中用MOUSEMOVE事件判断鼠标坐标是否到达窗体的边缘,如果是的话将鼠标指针改为可调整窗体大小的双向箭头.
**/
private void Form1_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
{
if(0 == e.X)
{
this.Cursor = Cursors.SizeWE;
}
//改成这样就可以了,很奇怪(不能写成:e.X >= this.Width)
else if(e.X >= this.Width-2)
{
this.Cursor = Cursors.SizeWE;
}
else
{
this.Cursor = Cursors.Default;
}
}
/**
2.但c#.net提供的cursor类只能做windows提供的光标形状之间的变换,cursor类貌似不支持动画以及多色的文件。我想要用自己的位图文件作为光标,应该怎么弄呢?
方案:使用鼠标文件定义自己的鼠标指针。
Cursor.Current=new Cursor(@"C:\my.cur");
OR: Cursor Cur=new Cursor(@"C:\my.cur");
this.Cursor = Cur;
在窗体的构造函数里加入上面的代码,就可以改变鼠标指针形状。
my.cur是鼠标位图文件,将鼠标图片直接作为文件加入到工程内,在工程内选择添加的文件后察看属性,修改生成属性值为嵌入的资源,这样就可以编译到exe里面取了。
**/