- Создание компонентов windows control library в VS 2015
- Решение
- Руководство. Создание элементов управления для Windows Forms How to: Author controls for Windows Forms
- Создание элемента управления To author a control
- Пошаговое руководство. Создание элемента управления, который использует преимущества функций времени разработки Walkthrough: Create a control that takes advantage of design-time features
- Предварительные требования Prerequisites
- Создание проекта Create the project
- Создание проекта библиотеки элементов управления Create the control library project
- Ссылка на проект пользовательского элемента управления Reference the Custom Control Project
- Определение пользовательского элемента управления и его пользовательского конструктора Define a Custom Control and Its Custom Designer
- Определение пользовательского элемента управления и его пользовательского конструктора To define a custom control and its custom designer
- Создание экземпляра пользовательского элемента управления Create an instance of your custom control
- Настройка проекта для отладки Design-Time Set Up the Project for Design-Time Debugging
- Контрольная точка Checkpoint
- Тестирование среды отладки и ассоциации конструктора To test the debugging environment and the designer association
- Реализация пользовательского элемента управления Implement the Custom Control
- Реализация пользовательского элемента управления To implement your custom control
- Создание дочернего элемента управления для пользовательского элемента управления Create a Child Control for Your Custom Control
- Создание дочернего элемента управления для пользовательского элемента управления To create a child control for your custom control
- Создание дочернего элемента управления Маркуибордер Create the MarqueeBorder Child Control
- Создание элемента управления Маркуибордер To create the MarqueeBorder control
- Создание пользовательского конструктора для тени и фильтрации свойств Create a Custom Designer to Shadow and Filter Properties
- Создание пользовательского конструктора для теневого копирования и свойств фильтра To create a custom designer to shadow and filter properties
- Обработку изменений компонентов Handle Component Changes
- Для управления изменениями компонентов To handle component changes
- Добавление команд конструктора в пользовательский конструктор Add Designer Verbs to your Custom Designer
- Добавление команд конструктора в пользовательские конструкторы To add designer verbs to your custom designers
- Создание настраиваемого UITypeEditor Create a Custom UITypeEditor
- Создание пользовательского редактора типов пользовательского интерфейса To create a custom UI type editor
- Создание элемента управления View для пользовательского UITypeEditor Create a View Control for your Custom UITypeEditor
- Создание элемента управления представления для пользовательского редактора типов пользовательского интерфейса To create a view control for your custom UI type editor
- Тестирование пользовательского элемента управления в конструкторе Test your Custom Control in the Designer
- Создание пользовательской реализации Маркуиконтрол To create a custom MarqueeControl implementation
- Дальнейшие действия Next steps
Создание компонентов windows control library в VS 2015
Всем привет.
Вот пытаюсь создать свой компонент под C# на VS 2015. Делаю по книге «C#. Разработка компонентов в MS Visual Studio 2005/2008». И на первом же шаге споткнулся о проблему, в VS 2015 я не могу создать новый проект «windows control library», поскольку его там нету.
Подскажите где его найти, или подскажите русско язычный ресурс где описано как на VS 2015 создать свой компонент.
Оцените мои кнопки написанные в Windows Forms Control Library
Писал код 15-18 часов без перерыва. Но думаю, не зря истратил время, сейчас я его доработаю еще.
WPF Control Library
Что надо установить чтобы можно было создавать WPF Control Library?(2008)
Создание Windows Forms проекта в Visual Studio 2015
Друзья, помогите, не дайте сойти с ума. Присутствует ли какая-то возможность заиметь привычные.
Создание графического приложения (Windows Forms) в Visual Studio 2013/2015/2017
Для последней версии Visual Studio 2013 (всех редакций): Создать проект->Visual C++->CLR->Пустой.
Решение
freeba, эм да я тоже нашел. Как то странно что так проморгал.
но и название у меня такое «windows form control library»
Ещё такой вопрос, я полагаю ты сам умееш создавать дополните компоненты для windows form?
Заказываю контрольные, курсовые, дипломные и любые другие студенческие работы здесь или здесь.
Динамическое создание компонентов в Windows Forms
Доброго времени суток! Пилю курсовую,возникла проблема с динамическим созданием компонентов в VS.
Как получить из библиотеки классов wpf user control library
Здравствуйте, все из заголовка ясно, под рукой только visual studio 2008 express, там из шаблонов.
Разработка приложений с использованием стандартных и дополнительных компонентов. Динамическое создание компонентов.
Здравствуйте! Помогите мне, пожалуйста. Условие задачи состоит в следующем: из списка выбираю.
Создание Delphi-компонентов. Правила создания компонентов
Текстовый файл содержит несколько вопросов и 4 варианта ответа , из которых только один.
Руководство. Создание элементов управления для Windows Forms How to: Author controls for Windows Forms
Элемент управления выполняет роль визуальной связи между пользователем и программой. A control represents a graphical link between the user and the program. Он может предоставлять или обрабатывать данные, принимать входные данные пользователя, реагировать на события или выполнять любые другие функции, устанавливающие связь между пользователем и приложением. A control can provide or process data, accept user input, respond to events, or perform any number of other functions that connect the user and the application. Поскольку элемент управления — это по сути компонент с графическим интерфейсом, он может выполнять любую функцию компонента и в то же время обеспечивать взаимодействие с пользователем. Because a control is essentially a component with a graphical interface, it can serve any function that a component does, as well as provide user interaction. Элементы управления создаются для конкретных целей, и процесс их создания входит в процесс программирования. Controls are created to serve specific purposes, and authoring controls is just another programming task. Ниже описан процесс создания элемента управления с учетом всего вышесказанного. With that in mind, the following steps represent an overview of the control authoring process. Ссылки указывают на дополнительные сведения об отдельных этапах. Links provide additional information on the individual steps.
Создание элемента управления To author a control
Определите, какую функцию или роль ваш элемент управления должен выполнять в приложении. Determine what you want your control to accomplish, or what part it will play in your application. При этом необходимо учитывать следующие факторы. Factors to consider are:
Какого рода графический интерфейс вам требуется? What kind of graphical interface do you need?
Какие взаимодействия с пользователем будет обрабатывать этот элемент управления? What specific user interactions will this control handle?
Обладают ли необходимыми функциональными возможностями какие-либо из существующих элементов управления? Is the functionality you need provided by any existing controls?
Можно ли получить необходимую функциональную возможность, объединив несколько элементов управления Windows Forms? Can you get the functionality you need by combining several Windows Forms controls?
Если для элемента управления требуется объектная модель, определите, каким образом функциональные возможности будут распределяться по объектной модели, и разделите их между элементом управления и подчиненными объектами. If you need an object model for your control, determine how functionality will be distributed throughout the object model, and divide up functionality between the control and any subobjects. Объектная модель может пригодиться при планировании сложного элемента управления, а также в случае, если вам требуется внедрить сразу несколько функциональных возможностей. An object model may be useful if you are planning a complex control, or want to incorporate several functionalities.
Определите необходимый тип элемента управления (например, пользовательский элемент управления, настраиваемый элемент управления, наследуемый элемент управления Windows Forms). Determine the type of control (for example, user control, custom control, inherited Windows Forms control) you need. Дополнительные сведения см. в разделах Рекомендации относительно типов элементов управления и Разновидности пользовательских элементов управления. For details, see Control Type Recommendations and Varieties of Custom Controls.
Представьте функции в качестве свойств, методов и событий элемента управления и его подчиненных объектов или вспомогательных структур и назначьте соответствующие уровни доступа (например, public, protected и т. д.). Express functionality as properties, methods, and events of the control and its subobjects or subsidiary structures, and assign appropriate access levels (for example, public, protected, and so on).
Если для элемента управления необходима пользовательская отрисовка, добавьте соответствующий код. If you need custom painting for your control, add code for it. Дополнительные сведения см. в разделе Рисование и отрисовка пользовательского элемента управления. For details, see Custom Control Painting and Rendering.
Если элемент управления наследуется от UserControl , можно проверить его поведение во время выполнения, создав проект элемента управления и запустив его в тестовом контейнере UserControl. If your control inherits from UserControl, you can test its runtime behavior by building the control project and running it in the UserControl Test Container. Дополнительные сведения см. в разделе как проверить поведение Run-Time UserControl. For more information, see How to: Test the Run-Time Behavior of a UserControl.
Кроме того, для тестирования и отладки элемента управления можно создать новый проект, например приложение Windows, и поместив его в контейнер. You can also test and debug your control by creating a new project, such as a Windows Application, and placing it into a container. Этот процесс демонстрируется как часть пошагового руководства. Создание составного элемента управления. This process is demonstrated as part of Walkthrough: Authoring a Composite Control.
При добавлении каждой функции добавляйте ее в тестовый проект для реализации новых функциональных возможностей. As you add each feature, add features to your test project to exercise the new functionality.
Повторите эти действия, добавив необходимые уточнения. Repeat, refining the design.
Упакуйте и разверните элемент управления. Package and deploy your control. Дополнительные сведения см. в разделе первое знакомство с развертыванием в Visual Studio. For details, see First look at deployment in Visual Studio.
Пошаговое руководство. Создание элемента управления, который использует преимущества функций времени разработки Walkthrough: Create a control that takes advantage of design-time features
Интерфейс времени разработки для пользовательского элемента управления можно расширить путем создания связанного пользовательского конструктора. The design-time experience for a custom control can be enhanced by authoring an associated custom designer.
В этой статье показано, как создать пользовательский конструктор для пользовательского элемента управления. This article illustrates how to create a custom designer for a custom control. Вы реализуете MarqueeControl тип и связанный класс конструктора с именем MarqueeControlRootDesigner . You’ll implement a MarqueeControl type and an associated designer class called MarqueeControlRootDesigner .
MarqueeControl Тип реализует вид, аналогичный области театра с анимированными индикаторами и мигающим текстом. The MarqueeControl type implements a display similar to a theater marquee with animated lights and flashing text.
Конструктор для этого элемента управления взаимодействует с средой разработки, чтобы обеспечить пользовательский интерфейс во время разработки. The designer for this control interacts with the design environment to provide a custom design-time experience. С помощью пользовательского конструктора можно собирать пользовательскую MarqueeControl реализацию с анимированными индикаторами и мигающим текстом во многих сочетаниях. With the custom designer, you can assemble a custom MarqueeControl implementation with animated lights and flashing text in many combinations. Собранный элемент управления можно использовать в форме, как и любой другой элемент управления Windows Forms. You can use the assembled control on a form like any other Windows Forms control.
По завершении работы с этим пошаговым руководством пользовательский элемент управления будет выглядеть примерно следующим образом: When you’re finished with this walkthrough, your custom control will look something like the following:
Предварительные требования Prerequisites
Для выполнения этого пошагового руководства вам потребуется Visual Studio. In order to complete this walkthrough, you’ll need Visual Studio.
Создание проекта Create the project
Первым шагом является создание проекта приложения. The first step is to create the application project. Этот проект будет использоваться для создания приложения, в котором размещается пользовательский элемент управления. You will use this project to build the application that hosts the custom control.
В Visual Studio создайте новый проект приложения Windows Forms и назовите его маркуиконтролтест. In Visual Studio, create a new Windows Forms Application project, and name it MarqueeControlTest.
Создание проекта библиотеки элементов управления Create the control library project
Добавьте в решение проект библиотеки элементов управления Windows Forms. Add a Windows Forms Control Library project to the solution. Назовите проект маркуиконтроллибрари. Name the project MarqueeControlLibrary.
С помощью Обозреватель решений удалите элемент управления проекта по умолчанию, удалив исходный файл с именем «UserControl1.cs» или «UserControl1. vb» в зависимости от выбранного языка. Using Solution Explorer, delete the project’s default control by deleting the source file named «UserControl1.cs» or «UserControl1.vb», depending on your language of choice.
Добавьте новый UserControl элемент в MarqueeControlLibrary проект. Add a new UserControl item to the MarqueeControlLibrary project. Присвойте новому исходному файлу базовое имя маркуиконтрол. Give the new source file a base name of MarqueeControl.
С помощью Обозреватель решений создайте новую папку в MarqueeControlLibrary проекте. Using Solution Explorer, create a new folder in the MarqueeControlLibrary project.
Щелкните правой кнопкой мыши папку конструктора и добавьте новый класс. Right-click the Design folder and add a new class. Назовите его маркуиконтролрутдесигнер. Name it MarqueeControlRootDesigner.
Необходимо использовать типы из сборки System. Design, поэтому добавьте эту ссылку в MarqueeControlLibrary проект. You’ll need to use types from the System.Design assembly, so add this reference to the MarqueeControlLibrary project.
Ссылка на проект пользовательского элемента управления Reference the Custom Control Project
MarqueeControlTest Для тестирования пользовательского элемента управления будет использоваться проект. You will use the MarqueeControlTest project to test the custom control. Тестовый проект будет получать информацию о пользовательском элементе управления при добавлении в нее ссылки на проект MarqueeControlLibrary . The test project will become aware of the custom control when you add a project reference to the MarqueeControlLibrary assembly.
В MarqueeControlTest проекте добавьте в сборку ссылку на проект MarqueeControlLibrary . In the MarqueeControlTest project, add a project reference to the MarqueeControlLibrary assembly. Обязательно используйте вкладку проекты в диалоговом окне Добавление ссылки вместо непосредственной ссылки на MarqueeControlLibrary сборку. Be sure to use the Projects tab in the Add Reference dialog box instead of referencing the MarqueeControlLibrary assembly directly.
Определение пользовательского элемента управления и его пользовательского конструктора Define a Custom Control and Its Custom Designer
Пользовательский элемент управления будет производным от UserControl класса. Your custom control will derive from the UserControl class. Это позволяет элементу управления содержать другие элементы управления, а также обеспечивает большую часть функциональных возможностей по умолчанию. This allows your control to contain other controls, and it gives your control a great deal of default functionality.
Пользовательский элемент управления будет иметь связанный пользовательский конструктор. Your custom control will have an associated custom designer. Это позволяет создать уникальный интерфейс разработки, специально предназначенный для пользовательского элемента управления. This allows you to create a unique design experience tailored specifically for your custom control.
Элемент управления связывается с конструктором с помощью DesignerAttribute класса. You associate the control with its designer by using the DesignerAttribute class. Поскольку вы разрабатываете все поведение пользовательского элемента управления во время разработки, Пользовательский конструктор будет реализовывать IRootDesigner интерфейс. Because you are developing the entire design-time behavior of your custom control, the custom designer will implement the IRootDesigner interface.
Определение пользовательского элемента управления и его пользовательского конструктора To define a custom control and its custom designer
Откройте MarqueeControl исходный файл в редакторе кода. Open the MarqueeControl source file in the Code Editor. В верхней части файла импортируйте следующие пространства имен: At the top of the file, import the following namespaces:
Добавьте в DesignerAttribute MarqueeControl объявление класса. Add the DesignerAttribute to the MarqueeControl class declaration. При этом пользовательский элемент управления связывается с его конструктором. This associates the custom control with its designer.
Откройте MarqueeControlRootDesigner исходный файл в редакторе кода. Open the MarqueeControlRootDesigner source file in the Code Editor. В верхней части файла импортируйте следующие пространства имен: At the top of the file, import the following namespaces:
Измените объявление MarqueeControlRootDesigner для наследования от DocumentDesigner класса. Change the declaration of MarqueeControlRootDesigner to inherit from the DocumentDesigner class. Примените, ToolboxItemFilterAttribute чтобы указать взаимодействие конструктора с панелью элементов. Apply the ToolboxItemFilterAttribute to specify the designer interaction with the Toolbox.
Определение MarqueeControlRootDesigner класса было заключено в пространство имен с именем маркуиконтроллибрари. Design. The definition for the MarqueeControlRootDesigner class has been enclosed in a namespace called MarqueeControlLibrary.Design. Это объявление помещает конструктор в специальное пространство имен, зарезервированное для типов, связанных с конструированием. This declaration places the designer in a special namespace reserved for design-related types.
Определите конструктор для MarqueeControlRootDesigner класса. Define the constructor for the MarqueeControlRootDesigner class. Вставьте WriteLine оператор в тело конструктора. Insert a WriteLine statement in the constructor body. Это будет полезно для отладки. This will be useful for debugging.
Создание экземпляра пользовательского элемента управления Create an instance of your custom control
Добавьте новый UserControl элемент в MarqueeControlTest проект. Add a new UserControl item to the MarqueeControlTest project. Присвойте новому исходному файлу базовое имя демомаркуиконтрол. Give the new source file a base name of DemoMarqueeControl.
Откройте DemoMarqueeControl файл в редакторе кода. Open the DemoMarqueeControl file in the Code Editor. В верхней части файла импортируйте MarqueeControlLibrary пространство имен: At the top of the file, import the MarqueeControlLibrary namespace:
Измените объявление DemoMarqueeControl для наследования от MarqueeControl класса. Change the declaration of DemoMarqueeControl to inherit from the MarqueeControl class.
Выполните построение проекта. Build the project.
Откройте форму Form1 в конструктор Windows Forms. Open Form1 in the Windows Forms Designer.
Найдите вкладку компоненты маркуиконтролтест на панели элементов и откройте ее. Find the MarqueeControlTest Components tab in the Toolbox and open it. Перетащите элемент DemoMarqueeControl из области элементов на форму. Drag a DemoMarqueeControl from the Toolbox onto your form.
Выполните построение проекта. Build the project.
Настройка проекта для отладки Design-Time Set Up the Project for Design-Time Debugging
При разработке настраиваемой среды разработки необходимо выполнить отладку элементов управления и компонентов. When you’re developing a custom design-time experience, it will be necessary to debug your controls and components. Существует простой способ настройки проекта, позволяющий выполнять отладку во время разработки. There is a simple way to set up your project to allow debugging at design time. Дополнительные сведения см. в разделе Пошаговое руководство. Отладка пользовательских элементов управления Windows Forms во время разработки. For more information, see Walkthrough: Debugging Custom Windows Forms Controls at Design Time.
Щелкните правой кнопкой мыши MarqueeControlLibrary проект и выберите пункт свойства. Right-click the MarqueeControlLibrary project and select Properties.
В диалоговом окне страницы свойств маркуиконтроллибрари выберите страницу Отладка . In the MarqueeControlLibrary Property Pages dialog box, select the Debug page.
В разделе действие при запуске выберите Запуск внешней программы. In the Start Action section, select Start External Program. Вы будете выполнять отладку отдельного экземпляра Visual Studio, поэтому нажмите кнопку с многоточием ( ), чтобы найти интегрированную среду разработки Visual Studio. You will be debugging a separate instance of Visual Studio, so click the ellipsis ( ) button to browse for the Visual Studio IDE. Имя исполняемого файла devenv.exe, а если вы установили в расположение по умолчанию, его путь: % ProgramFiles (x86)% \ Microsoft Visual Studio\2019 \ \Common7\IDE\devenv.exe. The name of the executable file is devenv.exe, and if you installed to the default location, its path is %ProgramFiles(x86)%\Microsoft Visual Studio\2019\ \Common7\IDE\devenv.exe.
Чтобы закрыть диалоговое окно, нажмите кнопку ОК. Select OK to close the dialog box.
Щелкните правой кнопкой мыши проект Маркуиконтроллибрари и выберите Назначить запускаемым проектом , чтобы включить эту конфигурацию отладки. Right-click the MarqueeControlLibrary project and select Set as StartUp Project to enable this debugging configuration.
Контрольная точка Checkpoint
Теперь все готово для отладки поведения пользовательского элемента управления во время разработки. You are now ready to debug the design-time behavior of your custom control. После определения правильности настройки среды отладки вы проверите связь между пользовательским элементом управления и пользовательским конструктором. Once you’ve determined that the debugging environment is set up correctly, you’ll test the association between the custom control and the custom designer.
Тестирование среды отладки и ассоциации конструктора To test the debugging environment and the designer association
Откройте исходный файл Маркуиконтролрутдесигнер в редакторе кода и поместите точку останова в WriteLine инструкцию. Open the MarqueeControlRootDesigner source file in the Code Editor and place a breakpoint on the WriteLine statement.
Нажмите клавишу F5 , чтобы запустить сеанс отладки. Press F5 to start the debugging session.
Создается новый экземпляр Visual Studio. A new instance of Visual Studio is created.
В новом экземпляре Visual Studio откройте решение Маркуиконтролтест. In the new instance of Visual Studio, open the MarqueeControlTest solution. Решение можно легко найти, выбрав последние проекты в меню файл . You can easily find the solution by selecting Recent Projects from the File menu. Файл решения Маркуиконтролтест. sln будет указан как последний использовавшийся файл. The MarqueeControlTest.sln solution file will be listed as the most recently used file.
Откройте в DemoMarqueeControl конструкторе. Open the DemoMarqueeControl in the designer.
Экземпляр отладки Visual Studio получает фокус и выполнение останавливается в точке останова. The debugging instance of Visual Studio obtains focus and execution stops at your breakpoint. Нажмите клавишу F5 , чтобы продолжить сеанс отладки. Press F5 to continue the debugging session.
На этом этапе все готово для разработки и отладки пользовательского элемента управления и связанного с ним пользовательского конструктора. At this point, everything is in place for you to develop and debug your custom control and its associated custom designer. Оставшаяся часть этой статьи сосредоточена на деталях реализации функций элемента управления и конструктора. The remainder of this article concentrates on the details of implementing features of the control and the designer.
Реализация пользовательского элемента управления Implement the Custom Control
MarqueeControl — Это UserControl с небольшой настройкой. The MarqueeControl is a UserControl with a little bit of customization. Он предоставляет два метода: Start , который запускает анимацию бегущей строки и Stop , в результате которой останавливается анимация. It exposes two methods: Start , which starts the marquee animation, and Stop , which stops the animation. Поскольку MarqueeControl содержит дочерние элементы управления, реализующие IMarqueeWidget интерфейс, Start и Stop перечисляет каждый дочерний элемент управления и вызывают StartMarquee StopMarquee методы и соответственно для каждого дочернего элемента управления, реализующего IMarqueeWidget . Because the MarqueeControl contains child controls that implement the IMarqueeWidget interface, Start and Stop enumerate each child control and call the StartMarquee and StopMarquee methods, respectively, on each child control that implements IMarqueeWidget .
Внешний вид MarqueeBorder MarqueeText элементов управления и зависит от макета, поэтому MarqueeControl переопределяет OnLayout метод и вызывает PerformLayout дочерние элементы управления этого типа. The appearance of the MarqueeBorder and MarqueeText controls is dependent on the layout, so MarqueeControl overrides the OnLayout method and calls PerformLayout on child controls of this type.
Это экстент MarqueeControl настроек. This is the extent of the MarqueeControl customizations. Функции времени выполнения реализуются MarqueeBorder MarqueeText элементами управления и, а функции времени разработки реализуются MarqueeBorderDesigner MarqueeControlRootDesigner классами и. The run-time features are implemented by the MarqueeBorder and MarqueeText controls, and the design-time features are implemented by the MarqueeBorderDesigner and MarqueeControlRootDesigner classes.
Реализация пользовательского элемента управления To implement your custom control
Откройте MarqueeControl исходный файл в редакторе кода. Open the MarqueeControl source file in the Code Editor. Реализуйте Start Stop методы и. Implement the Start and Stop methods.
Переопределите метод OnLayout . Override the OnLayout method.
Создание дочернего элемента управления для пользовательского элемента управления Create a Child Control for Your Custom Control
В MarqueeControl будет размещено два вида дочерних элементов управления: MarqueeBorder элемент управления и MarqueeText элемент управления. The MarqueeControl will host two kinds of child control: the MarqueeBorder control and the MarqueeText control.
MarqueeBorder : Этот элемент управления рисует границу «огни» вокруг ее границ. MarqueeBorder : This control paints a border of «lights» around its edges. Индикаторы помещаются поочередно, поэтому они перемещаются вокруг границы. The lights flash in sequence, so they appear to be moving around the border. Скорость, с которой мигают световые индикаторы, определяется свойством UpdatePeriod . The speed at which the lights flash is controlled by a property called UpdatePeriod . Несколько других пользовательских свойств определяют другие аспекты внешнего вида элемента управления. Several other custom properties determine other aspects of the control’s appearance. Два метода, называемые StartMarquee и StopMarquee , управляют началом и остановкой анимации. Two methods, called StartMarquee and StopMarquee , control when the animation starts and stops.
MarqueeText : Этот элемент управления рисует мигающую строку. MarqueeText : This control paints a flashing string. Как и MarqueeBorder элемент управления, скорость, с которой происходит мигание текста, определяется UpdatePeriod свойством. Like the MarqueeBorder control, the speed at which the text flashes is controlled by the UpdatePeriod property. MarqueeText Элемент управления также имеет StartMarquee методы и, StopMarquee Общие с MarqueeBorder элементом управления. The MarqueeText control also has the StartMarquee and StopMarquee methods in common with the MarqueeBorder control.
Во время разработки MarqueeControlRootDesigner позволяет добавлять эти два типа элементов управления в MarqueeControl любое сочетание. At design time, the MarqueeControlRootDesigner allows these two control types to be added to a MarqueeControl in any combination.
Общие функции двух элементов управления делятся на интерфейс с именем IMarqueeWidget . Common features of the two controls are factored into an interface called IMarqueeWidget . Это позволяет элементу MarqueeControl обнаруживать все дочерние элементы управления, связанные с областью, и давать им специальную обработку. This allows the MarqueeControl to discover any Marquee-related child controls and give them special treatment.
Чтобы реализовать функцию периодической анимации, вы будете использовать BackgroundWorker объекты из System.ComponentModel пространства имен. To implement the periodic animation feature, you will use BackgroundWorker objects from the System.ComponentModel namespace. Можно использовать Timer объекты, но при наличии большого числа IMarqueeWidget объектов один поток пользовательского интерфейса может не поддерживать анимацию. You could use Timer objects, but when many IMarqueeWidget objects are present, the single UI thread may be unable to keep up with the animation.
Создание дочернего элемента управления для пользовательского элемента управления To create a child control for your custom control
Добавьте в проект новый элемент класса MarqueeControlLibrary . Add a new class item to the MarqueeControlLibrary project. Присвойте новому исходному файлу базовое имя «Имаркуивиджет». Give the new source file a base name of «IMarqueeWidget.»
Откройте IMarqueeWidget исходный файл в редакторе кода и измените объявление с class на interface : Open the IMarqueeWidget source file in the Code Editor and change the declaration from class to interface :
Добавьте следующий код в интерфейс, IMarqueeWidget чтобы предоставить два метода и свойство, управляющие анимацией области. Add the following code to the IMarqueeWidget interface to expose two methods and a property that manipulate the marquee animation:
Добавьте в проект новый элемент пользовательского элемента управления MarqueeControlLibrary . Add a new Custom Control item to the MarqueeControlLibrary project. Присвойте новому исходному файлу базовое имя «Маркуитекст». Give the new source file a base name of «MarqueeText.»
Перетащите BackgroundWorker компонент из панели элементов на MarqueeText элемент управления. Drag a BackgroundWorker component from the Toolbox onto your MarqueeText control. Этот компонент позволит MarqueeText элементу управления обновляться в асинхронном режиме. This component will allow the MarqueeText control to update itself asynchronously.
В окне Свойства установите BackgroundWorker WorkerReportsProgress для компонента и WorkerSupportsCancellation свойства значение true. In the Properties window, set the BackgroundWorker component’s WorkerReportsProgress and WorkerSupportsCancellation properties to true. Эти параметры позволяют BackgroundWorker компоненту периодически вызывать ProgressChanged событие и отменять асинхронные обновления. These settings allow the BackgroundWorker component to periodically raise the ProgressChanged event and to cancel asynchronous updates.
Дополнительные сведения см. в разделе компонент BackgroundWorker. For more information, see BackgroundWorker Component.
Откройте MarqueeText исходный файл в редакторе кода. Open the MarqueeText source file in the Code Editor. В верхней части файла импортируйте следующие пространства имен: At the top of the file, import the following namespaces:
Измените объявление MarqueeText для наследования от Label и для реализации IMarqueeWidget интерфейса: Change the declaration of MarqueeText to inherit from Label and to implement the IMarqueeWidget interface:
Объявите переменные экземпляра, соответствующие предоставляемым свойствам, и инициализируйте их в конструкторе. Declare the instance variables that correspond to the exposed properties, and initialize them in the constructor. Поле определяет, следует ли закрасить isLit текст в цвет, заданный LightColor свойством. The isLit field determines if the text is to be painted in the color given by the LightColor property.
Реализовать интерфейс IMarqueeWidget . Implement the IMarqueeWidget interface.
StartMarquee Методы и StopMarquee вызывают BackgroundWorker RunWorkerAsync методы компонента и CancelAsync для запуска и завершения анимации. The StartMarquee and StopMarquee methods invoke the BackgroundWorker component’s RunWorkerAsync and CancelAsync methods to start and stop the animation.
CategoryАтрибуты и Browsable применяются к UpdatePeriod свойству, поэтому оно отображается в пользовательском разделе окно свойств с именем «бегущая строка». The Category and Browsable attributes are applied to the UpdatePeriod property so it appears in a custom section of the Properties window called «Marquee.»
Реализуйте методы доступа к свойствам. Implement the property accessors. Вы будете предоставлять клиентам два свойства: LightColor и DarkColor . You’ll expose two properties to clients: LightColor and DarkColor . Category Browsable К этим свойствам применяются атрибуты и, поэтому свойства отображаются в пользовательском разделе окно свойств с именем «бегущая строка». The Category and Browsable attributes are applied to these properties, so the properties appear in a custom section of the Properties window called «Marquee.»
Реализуйте обработчики для BackgroundWorker событий компонента DoWork и ProgressChanged . Implement the handlers for the BackgroundWorker component’s DoWork and ProgressChanged events.
DoWorkОбработчик событий UpdatePeriod закладывается на число миллисекунд, указанное затем ProgressChanged , вызывает событие, пока код не прекратит анимацию, вызвав CancelAsync . The DoWork event handler sleeps for the number of milliseconds specified by UpdatePeriod then raises the ProgressChanged event, until your code stops the animation by calling CancelAsync.
ProgressChangedОбработчик событий переключает текст между светлым и темным состоянием, чтобы придать ему внешний вид. The ProgressChanged event handler toggles the text between its light and dark state to give the appearance of flashing.
Переопределите OnPaint метод, чтобы включить анимацию. Override the OnPaint method to enable the animation.
Нажмите клавишу F6, чтобы построить решение. Press F6 to build the solution.
Создание дочернего элемента управления Маркуибордер Create the MarqueeBorder Child Control
MarqueeBorder Элемент управления является немного более сложным, чем MarqueeText элемент управления. The MarqueeBorder control is slightly more sophisticated than the MarqueeText control. Он имеет больше свойств, и анимация в OnPaint методе является более сложной. It has more properties and the animation in the OnPaint method is more involved. В принципе, он очень похож на MarqueeText элемент управления. In principle, it is quite similar to the MarqueeText control.
Поскольку MarqueeBorder элемент управления может иметь дочерние элементы управления, он должен знать о Layout событиях. Because the MarqueeBorder control can have child controls, it needs to be aware of Layout events.
Создание элемента управления Маркуибордер To create the MarqueeBorder control
Добавьте в проект новый элемент пользовательского элемента управления MarqueeControlLibrary . Add a new Custom Control item to the MarqueeControlLibrary project. Присвойте новому исходному файлу базовое имя «Маркуибордер». Give the new source file a base name of «MarqueeBorder.»
Перетащите BackgroundWorker компонент из панели элементов на MarqueeBorder элемент управления. Drag a BackgroundWorker component from the Toolbox onto your MarqueeBorder control. Этот компонент позволит MarqueeBorder элементу управления обновляться в асинхронном режиме. This component will allow the MarqueeBorder control to update itself asynchronously.
В окне Свойства установите BackgroundWorker WorkerReportsProgress для компонента и WorkerSupportsCancellation свойства значение true. In the Properties window, set the BackgroundWorker component’s WorkerReportsProgress and WorkerSupportsCancellation properties to true. Эти параметры позволяют BackgroundWorker компоненту периодически вызывать ProgressChanged событие и отменять асинхронные обновления. These settings allow the BackgroundWorker component to periodically raise the ProgressChanged event and to cancel asynchronous updates. Дополнительные сведения см. в разделе компонент BackgroundWorker. For more information, see BackgroundWorker Component.
В окне Свойства нажмите кнопку события . In the Properties window, select the Events button. Присоединение обработчиков DoWork для ProgressChanged событий и. Attach handlers for the DoWork and ProgressChanged events.
Откройте MarqueeBorder исходный файл в редакторе кода. Open the MarqueeBorder source file in the Code Editor. В верхней части файла импортируйте следующие пространства имен: At the top of the file, import the following namespaces:
Измените объявление MarqueeBorder для наследования от Panel и для реализации IMarqueeWidget интерфейса. Change the declaration of MarqueeBorder to inherit from Panel and to implement the IMarqueeWidget interface.
Объявите два перечисления для управления MarqueeBorder состоянием элемента управления: MarqueeSpinDirection , которое определяет направление, в котором огни вращается вокруг границы, и MarqueeLightShape , определяющий форму огней (квадратный или круглый). Declare two enumerations for managing the MarqueeBorder control’s state: MarqueeSpinDirection , which determines the direction in which the lights «spin» around the border, and MarqueeLightShape , which determines the shape of the lights (square or circular). Поместите эти объявления перед MarqueeBorder объявлением класса. Place these declarations before the MarqueeBorder class declaration.
Объявите переменные экземпляра, соответствующие предоставляемым свойствам, и инициализируйте их в конструкторе. Declare the instance variables that correspond to the exposed properties, and initialize them in the constructor.
Реализовать интерфейс IMarqueeWidget . Implement the IMarqueeWidget interface.
StartMarquee Методы и StopMarquee вызывают BackgroundWorker RunWorkerAsync методы компонента и CancelAsync для запуска и завершения анимации. The StartMarquee and StopMarquee methods invoke the BackgroundWorker component’s RunWorkerAsync and CancelAsync methods to start and stop the animation.
Поскольку MarqueeBorder элемент управления может содержать дочерние элементы управления, StartMarquee метод перечисляет все дочерние элементы управления и вызывает методы StartMarquee , реализующие IMarqueeWidget . Because the MarqueeBorder control can contain child controls, the StartMarquee method enumerates all child controls and calls StartMarquee on those that implement IMarqueeWidget . StopMarquee Метод имеет аналогичную реализацию. The StopMarquee method has a similar implementation.
Реализуйте методы доступа к свойствам. Implement the property accessors. MarqueeBorder Элемент управления имеет несколько свойств для управления его внешним видом. The MarqueeBorder control has several properties for controlling its appearance.
Реализуйте обработчики для BackgroundWorker событий компонента DoWork и ProgressChanged . Implement the handlers for the BackgroundWorker component’s DoWork and ProgressChanged events.
DoWorkОбработчик событий UpdatePeriod закладывается на число миллисекунд, указанное затем ProgressChanged , вызывает событие, пока код не прекратит анимацию, вызвав CancelAsync . The DoWork event handler sleeps for the number of milliseconds specified by UpdatePeriod then raises the ProgressChanged event, until your code stops the animation by calling CancelAsync.
ProgressChangedОбработчик событий увеличивает расположение «базового» освещения, из которого определяется светлое или темное состояние других источников света, и вызывает Refresh метод, чтобы элемент управления переводился в перерисовку. The ProgressChanged event handler increments the position of the «base» light, from which the light/dark state of the other lights is determined, and calls the Refresh method to cause the control to repaint itself.
Реализуйте вспомогательные методы IsLit и DrawLight . Implement the helper methods, IsLit and DrawLight .
IsLit Метод определяет цвет освещения в заданной позиции. The IsLit method determines the color of a light at a given position. Лампочки, которые являются «освещенными», рисуются цветом, заданным LightColor свойством, а те, которые являются «темными», рисуются цветом, заданным DarkColor свойством. Lights that are «lit» are drawn in the color given by the LightColor property, and those that are «dark» are drawn in the color given by the DarkColor property.
DrawLight Метод рисует источник освещения с помощью соответствующего цвета, формы и расположения. The DrawLight method draws a light using the appropriate color, shape, and position.
Переопределите методы OnLayout и OnPaint. Override the OnLayout and OnPaint methods.
OnPaintМетод рисует индикаторы вдоль краев MarqueeBorder элемента управления. The OnPaint method draws the lights along the edges of the MarqueeBorder control.
Поскольку OnPaint метод зависит от измерений MarqueeBorder элемента управления, его необходимо вызывать при каждом изменении макета. Because the OnPaint method depends on the dimensions of the MarqueeBorder control, you need to call it whenever the layout changes. Чтобы добиться этого, переопределите OnLayout и вызовите метод Refresh . To achieve this, override OnLayout and call Refresh.
Создание пользовательского конструктора для тени и фильтрации свойств Create a Custom Designer to Shadow and Filter Properties
MarqueeControlRootDesigner Класс предоставляет реализацию для корневого конструктора. The MarqueeControlRootDesigner class provides the implementation for the root designer. Помимо этого конструктора, который работает с MarqueeControl , необходим пользовательский конструктор, специально связанный с MarqueeBorder элементом управления. In addition to this designer, which operates on the MarqueeControl , you’ll need a custom designer that is specifically associated with the MarqueeBorder control. Этот конструктор предоставляет настраиваемое поведение, которое подходит для контекста пользовательского корневого конструктора. This designer provides custom behavior that is appropriate in the context of the custom root designer.
В частности, MarqueeBorderDesigner выполнит «тень» и отфильтрует определенные свойства MarqueeBorder элемента управления, изменив их взаимодействие с средой разработки. Specifically, the MarqueeBorderDesigner will «shadow» and filter certain properties on the MarqueeBorder control, changing their interaction with the design environment.
Перехват вызовов метода доступа к свойству компонента называется «тенью». Intercepting calls to a component’s property accessor is known as «shadowing.» Он позволяет конструктору отслеживанить значение, заданное пользователем, и при необходимости передать это значение в разрабатываемый компонент. It allows a designer to track the value set by the user and optionally pass that value to the component being designed.
В этом примере Visible Enabled Свойства и будут скрыты с помощью MarqueeBorderDesigner , что не позволяет пользователю сделать MarqueeBorder элемент управления невидимым или отключенным во время разработки. For this example, the Visible and Enabled properties will be shadowed by the MarqueeBorderDesigner , which prevents the user from making the MarqueeBorder control invisible or disabled during design time.
Конструкторы также могут добавлять и удалять свойства. Designers can also add and remove properties. В этом примере Padding свойство будет удалено во время разработки, так как MarqueeBorder элемент управления программно устанавливает заполнение на основе размера источников света, заданных LightSize свойством. For this example, the Padding property will be removed at design time, because the MarqueeBorder control programmatically sets the padding based on the size of the lights specified by the LightSize property.
Базовый класс для MarqueeBorderDesigner — ComponentDesigner , который содержит методы, которые могут изменять атрибуты, свойства и события, предоставляемые элементом управления во время разработки: The base class for MarqueeBorderDesigner is ComponentDesigner, which has methods that can change the attributes, properties, and events exposed by a control at design time:
При изменении открытого интерфейса компонента с помощью этих методов следует соблюдать следующие правила. When changing the public interface of a component using these methods, follow these rules:
Добавлять или удалять элементы только в PreFilter методах Add or remove items in the PreFilter methods only
Изменение существующих элементов только в PostFilter методах Modify existing items in the PostFilter methods only
Всегда вызывайте базовую реализацию сначала в PreFilter методах Always call the base implementation first in the PreFilter methods
Всегда вызывайте базовую реализацию последней в PostFilter методах Always call the base implementation last in the PostFilter methods
Соблюдение этих правил гарантирует, что все конструкторы в среде времени разработки будут иметь единообразное представление всех разрабатываемых компонентов. Adhering to these rules ensures that all designers in the design-time environment have a consistent view of all components being designed.
ComponentDesignerКласс предоставляет словарь для управления значениями затененных свойств, что освобождает вас от необходимости создавать конкретные переменные экземпляра. The ComponentDesigner class provides a dictionary for managing the values of shadowed properties, which relieves you of the need to create specific instance variables.
Создание пользовательского конструктора для теневого копирования и свойств фильтра To create a custom designer to shadow and filter properties
Щелкните правой кнопкой мыши папку конструктора и добавьте новый класс. Right-click the Design folder and add a new class. Присвойте исходному файлу базовое имя маркуибордердесигнер. Give the source file a base name of MarqueeBorderDesigner.
Откройте исходный файл Маркуибордердесигнер в редакторе кода. Open the MarqueeBorderDesigner source file in the Code Editor. В верхней части файла импортируйте следующие пространства имен: At the top of the file, import the following namespaces:
Измените объявление, MarqueeBorderDesigner чтобы наследовать от ParentControlDesigner . Change the declaration of MarqueeBorderDesigner to inherit from ParentControlDesigner.
Поскольку MarqueeBorder элемент управления может содержать дочерние элементы управления, MarqueeBorderDesigner наследует от ParentControlDesigner , который обрабатывает взаимодействие типа «родители-потомки». Because the MarqueeBorder control can contain child controls, MarqueeBorderDesigner inherits from ParentControlDesigner, which handles the parent-child interaction.
Переопределите базовую реализацию PreFilterProperties . Override the base implementation of PreFilterProperties.
Реализуйте свойства Enabled и Visible. Implement the Enabled and Visible properties. Эти реализации затениют свойства элемента управления. These implementations shadow the control’s properties.
Обработку изменений компонентов Handle Component Changes
MarqueeControlRootDesigner Класс предоставляет пользовательские возможности времени разработки для MarqueeControl экземпляров. The MarqueeControlRootDesigner class provides the custom design-time experience for your MarqueeControl instances. Большая часть функций времени разработки наследуется от DocumentDesigner класса. Most of the design-time functionality is inherited from the DocumentDesigner class. В коде будут реализованы две определенные настройки: обработка изменений компонентов и Добавление команд конструктора. Your code will implement two specific customizations: handling component changes, and adding designer verbs.
По мере разработки пользователями своих MarqueeControl экземпляров корневой конструктор будет отслеживанию изменений в MarqueeControl и его дочерних элементах управления. As users design their MarqueeControl instances, your root designer will track changes to the MarqueeControl and its child controls. Среда разработки предоставляет удобную службу IComponentChangeService для отслеживания изменений состояния компонента. The design-time environment offers a convenient service, IComponentChangeService, for tracking changes to component state.
Чтобы получить ссылку на эту службу, запросите среду с помощью GetService метода. You acquire a reference to this service by querying the environment with the GetService method. Если запрос выполнен успешно, конструктор может присоединить обработчик для ComponentChanged события и выполнить все задачи, необходимые для поддержания стабильного состояния во время разработки. If the query is successful, your designer can attach a handler for the ComponentChanged event and perform whatever tasks are required to maintain a consistent state at design time.
В случае MarqueeControlRootDesigner класса метод будет вызываться Refresh для каждого IMarqueeWidget объекта, содержащегося в MarqueeControl . In the case of the MarqueeControlRootDesigner class, you will call the Refresh method on each IMarqueeWidget object contained by the MarqueeControl . Это приведет к тому, что IMarqueeWidget объект будет правильно перерисовываться при изменении свойств, таких как его родительский элемент Size . This will cause the IMarqueeWidget object to repaint itself appropriately when properties like its parent’s Size are changed.
Для управления изменениями компонентов To handle component changes
Откройте MarqueeControlRootDesigner исходный файл в редакторе кода и переопределите Initialize метод. Open the MarqueeControlRootDesigner source file in the Code Editor and override the Initialize method. Вызовите базовую реализацию Initialize запроса и для IComponentChangeService . Call the base implementation of Initialize and query for the IComponentChangeService.
Реализуйте OnComponentChanged обработчик событий. Implement the OnComponentChanged event handler. Проверьте тип компонента отправки и, если он является IMarqueeWidget , вызовите его Refresh метод. Test the sending component’s type, and if it is an IMarqueeWidget , call its Refresh method.
Добавление команд конструктора в пользовательский конструктор Add Designer Verbs to your Custom Designer
Команда конструктора ― это команда меню, связанная с обработчиком событий. A designer verb is a menu command linked to an event handler. Команды конструктора добавляются в контекстное меню компонента во время разработки. Designer verbs are added to a component’s shortcut menu at design time. Для получения дополнительной информации см. DesignerVerb. For more information, see DesignerVerb.
В конструкторы вы добавите две команды конструктора: запустить тест и закончить тест. You will add two designer verbs to your designers: Run Test and Stop Test. Эти глаголы позволяют просматривать поведение во время выполнения в процессе MarqueeControl разработки. These verbs will allow you to view the run-time behavior of the MarqueeControl at design time. Эти команды будут добавлены в MarqueeControlRootDesigner . These verbs will be added to MarqueeControlRootDesigner .
При вызове запуска теста обработчик событий команды вызывает StartMarquee метод для MarqueeControl . When Run Test is invoked, the verb event handler will call the StartMarquee method on the MarqueeControl . При вызове метода » приостанавливается » обработчик событий команды вызывает StopMarquee метод для MarqueeControl . When Stop Test is invoked, the verb event handler will call the StopMarquee method on the MarqueeControl . Реализация StartMarquee StopMarquee методов и вызывает эти методы для вложенных элементов управления, которые реализуют IMarqueeWidget , поэтому все содержащиеся IMarqueeWidget в нем элементы управления также будут участвовать в тестировании. The implementation of the StartMarquee and StopMarquee methods call these methods on contained controls that implement IMarqueeWidget , so any contained IMarqueeWidget controls will also participate in the test.
Добавление команд конструктора в пользовательские конструкторы To add designer verbs to your custom designers
В MarqueeControlRootDesigner классе добавьте обработчики событий с именами OnVerbRunTest и OnVerbStopTest . In the MarqueeControlRootDesigner class, add event handlers named OnVerbRunTest and OnVerbStopTest .
Соедините эти обработчики событий с соответствующими командами конструктора. Connect these event handlers to their corresponding designer verbs. MarqueeControlRootDesigner наследует DesignerVerbCollection от своего базового класса. MarqueeControlRootDesigner inherits a DesignerVerbCollection from its base class. Вы создадите два новых DesignerVerb объекта и добавите их в эту коллекцию в Initialize методе. You will create two new DesignerVerb objects and add them to this collection in the Initialize method.
Создание настраиваемого UITypeEditor Create a Custom UITypeEditor
При создании пользовательской среды разработки для пользователей часто желательно создать пользовательское взаимодействие с окно свойств. When you create a custom design-time experience for users, it is often desirable to create a custom interaction with the Properties window. Это можно сделать, создав UITypeEditor . You can accomplish this by creating a UITypeEditor.
MarqueeBorder Элемент управления предоставляет несколько свойств в окно свойств. The MarqueeBorder control exposes several properties in the Properties window. Два из этих свойств MarqueeSpinDirection и MarqueeLightShape представлены перечислениями. Two of these properties, MarqueeSpinDirection and MarqueeLightShape are represented by enumerations. Чтобы продемонстрировать использование редактора типов пользовательского интерфейса, MarqueeLightShape свойство будет иметь связанный UITypeEditor класс. To illustrate the use of a UI type editor, the MarqueeLightShape property will have an associated UITypeEditor class.
Создание пользовательского редактора типов пользовательского интерфейса To create a custom UI type editor
Откройте MarqueeBorder исходный файл в редакторе кода. Open the MarqueeBorder source file in the Code Editor.
В определении MarqueeBorder класса объявите класс с именем LightShapeEditor , производным от UITypeEditor . In the definition of the MarqueeBorder class, declare a class called LightShapeEditor that derives from UITypeEditor.
Объявите IWindowsFormsEditorService переменную экземпляра с именем editorService . Declare an IWindowsFormsEditorService instance variable called editorService .
Переопределите метод GetEditStyle . Override the GetEditStyle method. Эта реализация возвращает DropDown , что указывает среде разработки, как отобразить LightShapeEditor . This implementation returns DropDown, which tells the design environment how to display the LightShapeEditor .
Переопределите метод EditValue . Override the EditValue method. Эта реализация запрашивает в среде разработки IWindowsFormsEditorService объект. This implementation queries the design environment for an IWindowsFormsEditorService object. В случае успеха создается LightShapeSelectionControl . If successful, it creates a LightShapeSelectionControl . DropDownControlМетод вызывается для запуска LightShapeEditor . The DropDownControl method is invoked to start the LightShapeEditor . Возвращаемое значение этого вызова возвращается в среду разработки. The return value from this invocation is returned to the design environment.
Создание элемента управления View для пользовательского UITypeEditor Create a View Control for your Custom UITypeEditor
MarqueeLightShape Свойство поддерживает два типа простых фигур: Square и Circle . The MarqueeLightShape property supports two types of light shapes: Square and Circle . Вы создадите пользовательский элемент управления, используемый исключительно в целях графического отображения этих значений в окно свойств. You will create a custom control used solely for the purpose of graphically displaying these values in the Properties window. Этот пользовательский элемент управления будет использоваться UITypeEditor для взаимодействия с окно свойств. This custom control will be used by your UITypeEditor to interact with the Properties window.
Создание элемента управления представления для пользовательского редактора типов пользовательского интерфейса To create a view control for your custom UI type editor
Добавьте новый UserControl элемент в MarqueeControlLibrary проект. Add a new UserControl item to the MarqueeControlLibrary project. Присвойте новому исходному файлу базовое имя лигхтшапеселектионконтрол. Give the new source file a base name of LightShapeSelectionControl.
Перетащите два Panel элемента управления из панели элементов в область LightShapeSelectionControl . Drag two Panel controls from the Toolbox onto the LightShapeSelectionControl . Назовите их squarePanel и circlePanel . Name them squarePanel and circlePanel . Расположите их параллельно. Arrange them side by side. Задайте Size для свойства обоих Panel элементов управления значение (60, 60). Set the Size property of both Panel controls to (60, 60). Присвойте Location свойству squarePanel элемента управления значение (8, 10). Set the Location property of the squarePanel control to (8, 10). Присвойте Location свойству circlePanel элемента управления значение (80, 10). Set the Location property of the circlePanel control to (80, 10). Наконец, задайте Size для свойства значение LightShapeSelectionControl (150, 80). Finally, set the Size property of the LightShapeSelectionControl to (150, 80).
Откройте LightShapeSelectionControl исходный файл в редакторе кода. Open the LightShapeSelectionControl source file in the Code Editor. В верхней части файла импортируйте System.Windows.Forms.Design пространство имен: At the top of the file, import the System.Windows.Forms.Design namespace:
Реализуйте Click обработчики событий squarePanel для circlePanel элементов управления и. Implement Click event handlers for the squarePanel and circlePanel controls. Эти методы вызывают CloseDropDown для завершения пользовательского UITypeEditor сеанса редактирования. These methods invoke CloseDropDown to end the custom UITypeEditor editing session.
Объявите IWindowsFormsEditorService переменную экземпляра с именем editorService . Declare an IWindowsFormsEditorService instance variable called editorService .
Объявите MarqueeLightShape переменную экземпляра с именем lightShapeValue . Declare a MarqueeLightShape instance variable called lightShapeValue .
В LightShapeSelectionControl конструкторе присоедините Click обработчики событий к squarePanel circlePanel событиям элементов управления и Click . In the LightShapeSelectionControl constructor, attach the Click event handlers to the squarePanel and circlePanel controls’ Click events. Кроме того, определите перегрузку конструктора, которая назначает MarqueeLightShape значение полю в среде разработки lightShapeValue . Also, define a constructor overload that assigns the MarqueeLightShape value from the design environment to the lightShapeValue field.
В Dispose методе отсоедините Click обработчики событий. In the Dispose method, detach the Click event handlers.
В обозревателе решений нажмите кнопку Показать все файлы. In Solution Explorer, click the Show All Files button. Откройте файл LightShapeSelectionControl.Designer.cs или Лигхтшапеселектионконтрол. Designer. vb и удалите определение метода по умолчанию Dispose . Open the LightShapeSelectionControl.Designer.cs or LightShapeSelectionControl.Designer.vb file, and remove the default definition of the Dispose method.
Реализуйте свойство LightShape . Implement the LightShape property.
Переопределите метод OnPaint . Override the OnPaint method. В этой реализации будет нарисован закрашенный квадрат и круг. This implementation will draw a filled square and circle. Он также выделяет выбранное значение, рисуя границу вокруг одной или другой фигуры. It will also highlight the selected value by drawing a border around one shape or the other.
Тестирование пользовательского элемента управления в конструкторе Test your Custom Control in the Designer
На этом этапе можно построить MarqueeControlLibrary проект. At this point, you can build the MarqueeControlLibrary project. Протестируйте реализацию, создав элемент управления, который наследует от MarqueeControl класса и использует его в форме. Test your implementation by creating a control that inherits from the MarqueeControl class and using it on a form.
Создание пользовательской реализации Маркуиконтрол To create a custom MarqueeControl implementation
Откройте DemoMarqueeControl в конструкторе Windows Forms. Open DemoMarqueeControl in the Windows Forms Designer. При этом создается экземпляр типа, который DemoMarqueeControl отображается в экземпляре MarqueeControlRootDesigner типа. This creates an instance of the DemoMarqueeControl type and displays it in an instance of the MarqueeControlRootDesigner type.
На панели элементов откройте вкладку компоненты маркуиконтроллибрари . Вы увидите MarqueeBorder MarqueeText элементы управления и, доступные для выбора. In the Toolbox, open the MarqueeControlLibrary Components tab. You will see the MarqueeBorder and MarqueeText controls available for selection.
Перетащите экземпляр MarqueeBorder элемента управления на DemoMarqueeControl поверхность конструктора. Drag an instance of the MarqueeBorder control onto the DemoMarqueeControl design surface. Закрепление этого MarqueeBorder элемента управления в родительском элементе управления. Dock this MarqueeBorder control to the parent control.
Перетащите экземпляр MarqueeText элемента управления на DemoMarqueeControl поверхность конструктора. Drag an instance of the MarqueeText control onto the DemoMarqueeControl design surface.
Создайте решение. Build the solution.
Щелкните правой кнопкой мыши DemoMarqueeControl и в контекстном меню выберите пункт запустить тест , чтобы запустить анимацию. Right-click the DemoMarqueeControl and from the shortcut menu select the Run Test option to start the animation. Нажмите кнопку » Закрыть тест «, чтобы прерывать анимацию. Click Stop Test to stop the animation.
Откройте форму Form1 в конструкторе. Open Form1 in Design view.
Поместите два Button элемента управления в форму. Place two Button controls on the form. Присвойте им имя startButton и и stopButton измените Text значения свойств на Start и останавливаться соответственно. Name them startButton and stopButton , and change the Text property values to Start and Stop, respectively.
Реализуйте Click обработчики событий для обоих Button элементов управления. Implement Click event handlers for both Button controls.
На панели элементов откройте вкладку компоненты маркуиконтролтест . Вы увидите DemoMarqueeControl Доступные для выбора. In the Toolbox, open the MarqueeControlTest Components tab. You will see the DemoMarqueeControl available for selection.
Перетащите экземпляр DemoMarqueeControl на поверхность конструктора Form1 . Drag an instance of DemoMarqueeControl onto the Form1 design surface.
В Click обработчиках событий вызовите Start методы и Stop для DemoMarqueeControl . In the Click event handlers, invoke the Start and Stop methods on the DemoMarqueeControl .
Задайте MarqueeControlTest проект в качестве запускаемого проекта и запустите его. Set the MarqueeControlTest project as the startup project and run it. Вы увидите форму, в которой отображается DemoMarqueeControl . You will see the form displaying your DemoMarqueeControl . Нажмите кнопку запустить , чтобы запустить анимацию. Select the Start button to start the animation. Вы увидите, что текст мигает и индикаторы перемещаются вокруг границы. You should see the text flashing and the lights moving around the border.
Дальнейшие действия Next steps
В MarqueeControlLibrary примере демонстрируется простая реализация пользовательских элементов управления и связанных с ними конструкторов. The MarqueeControlLibrary demonstrates a simple implementation of custom controls and associated designers. Сделать этот пример более сложным можно несколькими способами: You can make this sample more sophisticated in several ways:
Измените значения свойств для в DemoMarqueeControl конструкторе. Change the property values for the DemoMarqueeControl in the designer. Добавьте дополнительные MarqueBorder элементы управления и закрепите их в своих родительских экземплярах, чтобы создать вложенный результат. Add more MarqueBorder controls and dock them within their parent instances to create a nested effect. Экспериментируйте с различными настройками для UpdatePeriod и свойств, связанных с источниками. Experiment with different settings for the UpdatePeriod and the light-related properties.
Создайте собственные реализации IMarqueeWidget . Author your own implementations of IMarqueeWidget . Например, можно создать мигающий знак «Neon» или анимированный знак с несколькими изображениями. You could, for example, create a flashing «neon sign» or an animated sign with multiple images.
Дальнейшая настройка взаимодействия во время разработки. Further customize the design-time experience. Можно попытаться затенить больше Enabled свойств Visible , чем и, и добавить новые свойства. You could try shadowing more properties than Enabled and Visible, and you could add new properties. Добавьте новые команды конструктора для упрощения распространенных задач, таких как закрепление дочерних элементов управления. Add new designer verbs to simplify common tasks like docking child controls.
Лицензия MarqueeControl . License the MarqueeControl .
Управление сериализацией элементов управления и созданием кода для них. Control how your controls are serialized and how code is generated for them. Дополнительные сведения см. в разделе Динамическое создание и компиляция исходного кода. For more information, see Dynamic Source Code Generation and Compilation.