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

查看:133
本文介绍了如何从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).

我想在我的应用程序项目中使用它。 strong>,但是一旦组件被创建,我得到以下异常:

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)

我在这里缺少什么?

编辑

包项目中资源的调用代码如下所示:

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');

同样例外。

编辑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文件包含到我的项目中,所以资源将被编译成。每次构建后都可以。我猜这个伎俩。感谢所有答案。

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天全站免登陆