将鼠标指针处的较小图像叠加到图片框上 [英] Overlay a smaller image at mouse pointer onto a PictureBox
问题描述
我刚刚开始为 C# 应用程序开发 Winforms GUI,想知道以下是否可行?
I'm just starting to develop the Winforms GUI for a C# application and was wondering if the following was possible?
我希望在图片框中显示大图像(很容易完成),然后当鼠标指针位于较大图像上时,将第二个较小的图像覆盖在鼠标位置的大图像上.如果可能,我希望叠加图像部分透明.
I wish to display a large image in a Picture Box (easily done) and then have a second smaller image overlay onto the large image at the mouse position, when the mouse pointer is over the larger image. If possible I would like the overlay image to be partially transparent.
由于 GUI 设计还处于早期阶段,如果这会使我的要求更容易,我可以将其更改为 WPF.
As the GUI design is at an early stage I can change it to WPF if this would make what I'm asking any easier.
非常感谢,
安迪.
推荐答案
那是 Winforms 中的单行,只需更改 PictureBox.Cursor 属性:
That's a one-liner in Winforms, just change the PictureBox.Cursor property:
pictureBox1.Cursor = new Cursor(new MemoryStream(Properties.Resources.ExampleCursor));
如果您需要任意图像,则需要将位图转换为光标.一个小辅助函数来做到这一点:
If you need an arbitrary image then you need to convert the bitmap to a cursor. A little helper function to do it:
using System.Reflection;
...
private static Cursor CursorFromBitmap(Bitmap bmp) {
var hicon = bmp.GetHicon();
var cursor = new Cursor(hicon);
var fi = typeof(Cursor).GetField("ownHandle", BindingFlags.NonPublic | BindingFlags.Instance);
fi.SetValue(cursor, true);
return cursor;
}
使用一些反射技巧来避免必须跟踪句柄并显式销毁它.像这样使用它:
With some reflection trickery to avoid having to keep track of the handle and destroy it explicitly. Use it like this:
pictureBox1.Cursor = CursorFromBitmap(Properties.Resources.ExampleImage);
这篇关于将鼠标指针处的较小图像叠加到图片框上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!