如何在 Delphi 中添加和使用来自自定义包/组件的资源? [英] How to add and use a resource from a custom package/component in Delphi?

查看:24
本文介绍了如何在 Delphi 中添加和使用来自自定义包/组件的资源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想制作一个组件,该组件使用在我的包项目中编译的一些资源.我的组件将在运行时(在其构造函数中)尝试使用此资源(PNG 图像).

I want to make a component that uses some resources compiled in my package's project. My component will try to use this resource (a PNG image) during runtime (at its constructor).

我想在我的应用程序的项目中使用它,但是一旦创建了组件,我就会收到以下异常:

I want to use it in my application's project, but as soon as the component gets created, I get the following exception:

First chance exception at $7579B9BC. Exception class EResNotFound with message 'Resource xxx not found'. Process yyy.exe (6060)

我在这里遗漏了什么?

编辑

包的项目中资源的调用代码是这样的:

The calling code for the resource in the package's project is like this:

Png.LoadFromResourceName(HInstance, 'png_resource_name');

编辑 2

按照 David 的建议,我尝试使用函数 GetModuleHandle,但如果我从包的项目应用程序的项目调用它,它将始终返回 0.包的项目中被调用的代码是这样的:

As suggested by David, I tried using the function GetModuleHandle, but it will always return 0 if I call it from the package's project or the application's project. The code being called in the package's project is like this:

PackageModuleHandle := GetModuleHandle(PChar('my_package.bpl'));
Png := TPngImage.Create;
Png .LoadFromResourceName(PackageModuleHandle, 'png_resource_name');

bpl 文件的绝对路径也不起作用.

Absolute paths to the bpl file won't work either.

编辑 3

基于新答案的新尝试:

PackageModuleHandle := FindClassHInstance(TMyComponent);
Png := TPngImage.Create;
Png .LoadFromResourceName(PackageModuleHandle, 'png_resource_name');

由于相同的异常而失败.

Fails with the same exception.

编辑 4

使用 ResourceHacker,如果我使用得当,资源似乎不在我的 bpl 文件中.我可能做错了什么?这么简单的功能,似乎是一件很复杂的事情.

Using ResourceHacker, and if I used it right, the resources doesn't seem to be in my bpl file. What could I be doing wrong about this? Seems such a complicated matter to such a simple feature.

结论

我必须在 {$R *.res} 行之后将我的包的 .res 文件添加到包的 .dpr 中.像这样:

I had to add the .res file of my package to the package's .dpr just after the {$R *.res} line. Like this:

{$R *.res}
{$R 'my_pacakge.res'}

此外,我必须将 my_package.rc 文件包含到我的项目中,这样资源会在每次构建后编译为 .res.我想,这确实奏效了.谢谢大家的回答.

Also, I had to include the my_package.rc file to my project, so the resources would get compiled to the .res after each build. That did the trick, I guess. Thanks for all the answers.

推荐答案

你需要使用FindClassHInstance(),指定你的组件的类类型,而不是使用全局的HInstance 变量或 GetModuleHandle().这样,无论包是静态链接还是动态链接到主可执行文件中,您都可以获得正确的模块句柄.

You need to use FindClassHInstance(), specifying your component's class type, instead of using the global HInstance variable or GetModuleHandle(). That way, you obtain the correct module handle regardless of whether the package gets statically linked or dynamically linked into the main executable.

这篇关于如何在 Delphi 中添加和使用来自自定义包/组件的资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆