2016-02-09 102 views
1

我创建了一个.cur文件与内部填充椭圆一个简单的光标。动态更改光标大小在c#

我希望这Cursor表现得像一个“刷光标”,意思是,如果我改变笔刷的厚度,Cursor的大小将会改变(我也想改变Cursor的颜色)。

下面是我使用的代码:

var customCursor = new Cursor(@"CustomCursor.cur"); 
Mouse.OverrideCursor = currentCursor; 

可这样的事情做什么?有没有更好的方法来做到这一点?

+0

这会是你在找什么? http://www.c-sharpcorner.com/UploadFile/mahesh/cursors-in-C-Sharp/ – Jacobr365

+0

不太。我遇到了这个,但它没有提供任何选项来在运行时动态更改颜色的大小/颜色。 – Idanis

+0

对于颜色,你可能不得不使光标在不同颜色的几本,然后就换​​到一个你想要的颜色。适用于在鼠标悬停时突出显示按钮。假设它将与光标一样工作。 – Jacobr365

回答

1

我以前使用过这一点,它的工作原理。

Cursor CreateCursor(double rx, double ry, SolidColorBrush brush, Pen pen) 
{ 
    var vis = new DrawingVisual(); 
    using (var dc = vis.RenderOpen()) 
    { 
     dc.DrawRectangle(brush, new Pen(Brushes.Black, 0.1), new Rect(0, 0, rx, ry)); 
     dc.Close(); 
    } 
    var rtb = new RenderTargetBitmap(64, 64, 96, 96, PixelFormats.Pbgra32); 
    rtb.Render(vis); 

    using (var ms1 = new MemoryStream()) 
    { 
     var penc = new PngBitmapEncoder(); 
     penc.Frames.Add(BitmapFrame.Create(rtb)); 
     penc.Save(ms1); 

     var pngBytes = ms1.ToArray(); 
     var size = pngBytes.GetLength(0); 

     //.cur format spec http://en.wikipedia.org/wiki/ICO_(file_format) 
     using (var ms = new MemoryStream()) 
     { 
      {//ICONDIR Structure 
       ms.Write(BitConverter.GetBytes((Int16)0), 0, 2);//Reserved must be zero; 2 bytes 
       ms.Write(BitConverter.GetBytes((Int16)2), 0, 2);//image type 1 = ico 2 = cur; 2 bytes 
       ms.Write(BitConverter.GetBytes((Int16)1), 0, 2);//number of images; 2 bytes 
      } 

      {//ICONDIRENTRY structure 
       ms.WriteByte(32); //image width in pixels 
       ms.WriteByte(32); //image height in pixels 

       ms.WriteByte(0); //Number of Colors in the color palette. Should be 0 if the image doesn't use a color palette 
       ms.WriteByte(0); //reserved must be 0 

       ms.Write(BitConverter.GetBytes((Int16)(rx/2.0)), 0, 2);//2 bytes. In CUR format: Specifies the horizontal coordinates of the hotspot in number of pixels from the left. 
       ms.Write(BitConverter.GetBytes((Int16)(ry/2.0)), 0, 2);//2 bytes. In CUR format: Specifies the vertical coordinates of the hotspot in number of pixels from the top. 

       ms.Write(BitConverter.GetBytes(size), 0, 4);//Specifies the size of the image's data in bytes 
       ms.Write(BitConverter.GetBytes((Int32)22), 0, 4);//Specifies the offset of BMP or PNG data from the beginning of the ICO/CUR file 
      } 

      ms.Write(pngBytes, 0, size);//write the png data. 
      ms.Seek(0, SeekOrigin.Begin); 
      return new Cursor(ms); 
     } 
    } 
} 

然后,设置它,您拨打:

Mouse.OverrideCursor = CreateCursor(50,50, Brushes.Gold, null); 

来源:https://gist.github.com/kip9000/4201899

+0

非常感谢!有用。 – Idanis