如何在C#Winforms中创建嵌入式资源游标?

Ste*_*ows 3 c# cursor winforms

我正在尝试将自定义光标添加到C#Winforms应用程序作为嵌入式资源.似乎嵌入部分不能像文档所暗示的那样工作.

如果我在运行时从文件加载光标,它就可以了:

myMagCursor = new Cursor("../Resources/magnify.cur");
Run Code Online (Sandbox Code Playgroud)

所以看起来光标文件很好.我在MSDN上按照这个信息 嵌入了游标(来自C#示例中的注释):

//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"
Run Code Online (Sandbox Code Playgroud)

然后试着像这样使用它:

myMagCursor = new Cursor(GetType(), "magnify.cur");
Run Code Online (Sandbox Code Playgroud)

哪个给出了空引用异常,我假设因为找不到资源.我也试过这种方法(在网络的其他地方找到):

namespace Piccolo.Forms
{
    public partial class Hanger
    {
    ...
        Assembly asm = Assembly.GetExecutingAssembly();
        using( Stream resStream = asm.GetManifestResourceStream("Piccolo.magnify.cur") )
        {
            myMagCursor = new Cursor( resStream );
        }
Run Code Online (Sandbox Code Playgroud)

我试过"Piccolo.magnify.cur","Piccolo.Forms.magnify.cur","Piccolo.Forms.Hanger.magnify.cur","Hanger.magnify.cur"等我推断光标还没有嵌入式.

光标文件位于Resources文件夹中,其中包含一堆.ico,.png和.jpg文件,这些文件都可以作为工具条按钮正常工作,并显示在项目的"Resources.resx"文件(?)中.他们都没有"嵌入式资源"属性.我的光标文件确实有"嵌入式资源",但没有出现在"Resources.resx"中.

我对光标文件缺少什么才能正确嵌入?

k.s*_*r31 7

我已经获得了第二种在WPF应用程序中工作的方法.无论如何,该部分应该相同,因为它们都使用相同类型的资源流.这是我成功使用的线.

canvas1.Cursor = new Cursor(Assembly.GetExecutingAssembly().GetManifestResourceStream("WpfApplication2.mallet.cur"));
Run Code Online (Sandbox Code Playgroud)

最有可能的是,您将光标放在某种文件夹中,因此"Piccolo.magnify.cur"部分是错误的.您可以做的是将所有资源流名称打印到文本框或其他内容,以确切了解您应该放在那里的内容.使用以下内容完成此操作:

String[] resourceNames = Assembly.GetExecutingAssembly().GetManifestResourceNames();
Run Code Online (Sandbox Code Playgroud)

并根据您的选择打印出来.这应该指向正确的方向.


Lar*_*ech 5

对于游标,您可以这样做:

using (MemoryStream ms = new MemoryStream(Properties.Resources.magnify))
{
  myMagCursor = New Cursor(ms);
}
Run Code Online (Sandbox Code Playgroud)

但是,希望你不要期望看到它的颜色.


Han*_*ant 5

获得用于工作的过载很麻烦.它有永无止境的命名空间问题.到目前为止,最好的方法是通过Project + Properties,Resources选项卡添加游标作为资源.单击"添加资源"按钮的箭头,"添加现有文件",然后选择.cur文件.

在运行时,您可以使用Properties.Resources.cursorname财产.返回一个byte [],你把它打成一个代码如下的游标:

 this.Cursor = new Cursor(new System.IO.MemoryStream(Properties.Resources.arrow_i));
Run Code Online (Sandbox Code Playgroud)

注意使用MemoryStream将byte []转换为流,以便Cursor(Stream)重载起作用.