Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
CSharp_Prog_Guide.doc
Скачиваний:
16
Добавлен:
16.11.2019
Размер:
6.22 Mб
Скачать

Добавление ресурсов в проекты

Для добавления ресурсов в проект необходимо щелкнуть правой кнопкой мыши узел Свойства в проекте в Обозревателе решений, щелкнуть Открыть, а затем на странице Ресурсы в Конструкторе проектов нажать кнопку Добавить ресурс.

Ресурсы можно добавить в проект в качестве связанных ресурсов (внешние файлы) или как внедренные ресурсы (внедренные непосредственно в файл RESX).

  • При добавлении связанного ресурса в файле RESX со сведениями о ресурсах проекта будет указан только относительный путь на файл ресурса на диске. Если в качестве связанных ресурсов добавить изображения, видео или другие сложные файлы, их можно будет изменять в редакторе по умолчанию, сопоставленном с соответствующим типом файла в конструкторе ресурсов.

  • В случае внедренных ресурсов, данные хранятся непосредственно в файле ресурсов проекта (RESX). Строки могут храниться только как внедренные ресурсы.

Editing Resources

The Resource Designer enables you to add and modify project resources during development by associating a default application for editing each resource. You access the Resource Designer by right-clicking Properties in Solution Explorer, clicking Open, and then clicking the Resources tab in Project Designer. For more information, see Resources Page, Project Designer. The following illustration shows the Resource Designer menu options:

To edit embedded resources, you must work directly in the .resx file to manipulate the individual characters or bytes. That is why it is more convenient to store complex file types as linked resources during development. You can use the Binary Editor to edit resource files, including the .resx file, at the binary level in either hexadecimal or ASCII format. You can use the Image Editor to edit icons and cursors as well as .jpeg and GIF files that are stored as linked resources. You can also choose other applications as editors for these file types.

Редактирование ресурсов

Редактор ресурсов позволяет добавлять и изменять ресурсы проектов во время развертывания путем сопоставления приложения по умолчанию для редактирования каждого ресурса. Чтобы вызвать конструктор ресурсов, необходимо в Обозревателе решений щелкнуть “Свойства”, затем Открыть и перейти на вкладку Ресурсы в конструкторе проектов. Дополнительные сведения см. в разделе Страница "Ресурсы" в конструкторе проектов. На следующем рисунке показаны пункты меню конструктора ресурсов.

Для редактирования ресурсов необходимо работать непосредственно в файле RESX, чтобы управлять отдельными символами или байтами. Именно поэтому сложные типы файлов удобно хранить в виде связанных ресурсов во время развертывания. Двоичный редактор можно использовать для редактирования файлов ресурсов, в том числе файла RESX, на двоичном уровне в шестнадцатеричном формате или формате ASCII. С помощью Редактор изображений можно редактировать значки и курсоры, а также файлы JPEG и GIF, хранящиеся в качестве связанных ресурсов. В качестве редакторов этих типов файлов можно выбрать и другие приложения.

Compiling Resources into Assemblies

When you build your application, Visual Studio invokes the resgen.exe tool to convert your application resources into an internal class called Resources. This class is contained in the Resources.Designer.cs file which is nested under the Resources.resx file in Solution Explorer. The Resources class encapsulates all your project resources into static readonly get properties as a way of providing strongly-typed resources at run-time. When you build through the Visual C# IDE, all the encapsulated resource data, including both the resources that were embedded into the .resx file and the linked files, is compiled directly into the application assembly (the .exe or .dll file). In other words, the Visual C# IDE always uses the /resource compiler option. If you build from the command line, you can specify the /linkresource compiler option that will enable you to deploy resources in a separate file from the main application assembly. This is an advanced scenario and is only necessary in certain rare situations. A more common scenario for deploying resources separately from the main application assembly is to use satellite assemblies as discussed below.

Accessing Resources at Run-Time

To access a resource at run-time, simply reference it as you would any other class member. The following example shows how to retrieve a bitmap resource that you named Image01. Note that the Resources class is in a namespace called <projectName>.Properties, so you must either user the fully qualified name for each resource or else add the appropriate using directive in the source file from which you are accessing the Resources class.

System.Drawing.Bitmap bitmap1 = myProject.Properties.Resources.Image01;

Internally the get property uses the ResourceManager class to create a new instance of the object.