Воробьёв Станислав
В этой статье я хотел бы описать создание простенького COM компонента на Visual C++, он, в принципе, ничего полезного делать не будет, он просто послужит моделью для создания COM'ов, которые будут более функцианальными.
Итак приступим, откройте Visual C++, в меню New выберите ATL COM AppWizard,затем напишите в поле Project Name: MyCom и нажмите Ok. В этом Wizard'е всего 1 шаг, вы должны выбрать тип, выберите DLL, вы также можете, например, добавить поддержку MFC, но мы не будем этого делать, т.к наш компонент не будет каким-то очень замудрёным, он будет простым и будет служить для ознакомительных целей, поэтому не надо нагружать его дополнительными килобайтами библиотеки MFC.
Проект создан, теперь надо добавить в него COM-объект, нажмите на Insert в главном меню и выберите New ATL Object...
Выберите категорию Objects и объект Simple Object. Теперь вы видите диалоговое окно, щёлкните по вкладке Names, В поле Short Name введите имя компонента, который вы предполагаете создать, пусь это будет MyObject, заметьте что все остальные поля заполняются автоматически, рекомендуется так и оставить.
Если хотите, можете изменить поле type, это просто описание COM'а, давайте введём My first Class. Теперьщёлкнитеповкладке Attributes, выберите Single threading model, Custom interface и No Aggregation. Всё, вы создали компонент, ну а теперь надо сделать его рабочим. Во вкладке ClassView вы видите созданный вами класс CMyObject и интерфейс IMyObject, он нужен для создания библиотеки типов.
Выберите интерфейс IMyObject во вкладке ClassView, щёлкните по нему правой кнопкой мыши и из контекстного меню выберите Add Method...
Теперь вы видите перед собой диалоговое окно Add Method to Interface, в поле Method Name введите ShowMessageBox, а в поле parameters введите:[in] const BSTR StringToWrite, [out,retval] long *Result.Поясняю в кратце эту строку: [in] указывает на то, что StringToWrite вводится в функцию, а [out] на то, что этот параметр возвращается, [retval] означает, что этот параметр будет возвращаться всей функцией, это нужно для того, чтобы компонент мог работать, например, в среде Visual Basic, т.к VB не поддерживает тип данных HRESULT, который возвращает эта функция. Вместо того чтобы возвращать данное типа HRESULT, в VB этот метод вернёт данное типа long. Метод создан. В нашем примере он будет показывать пользователю окно сообщение с текстом, находящимся в перемменой StringToWrite.
Давайте теперь создадим свойство строкового типа, которое будет отвечать за заголовок окна сообщения, можно было бы конечно в свойство ShowMessageBox добавить ешё один [in] параметр, который бы отвечал за это, но щас наша цель разработать демонстрационный компонент, поэтому создадим свойство. Щёлкните вновь по интерфейсу IMyObject правой кнопкой мыши и выберите Add Property... В поле Property Type выберите BSTR, а в поле Property Name введите Caption и щёлкните на Ok. Вовкладке ClassView выберитеСMyObject->IMyObject вывидите 2 функции: get_Caption, put_Caption. Функция put_Caption вызывается, когда вы присваиваете свойству Caption новое значение, а get_Caption, когда считываете. В интерфейсе этих функций не будет, можете щас откомпилировать проект и зайти в Visual Basic.
< P> Выберите в менюProject->References, найдите в списке MyCom 1.0 Type Library отметьте его галочкой и щёлкните на Ok. Вмодуленапишите:
Dim MyObj As New MyObject
Private Sub Form_Load()
MyObj.
End Sub
Перед вами открывается список методов и свойств, как видите здесь только 1 метод ShowMessageBox и только 1 свойство Caption. Ни то ни другое пока не работает, потому что мы ещё не реализовали метод ShowMessageBox и функции put_Caption и get_Caption. Давайте заставим их работать! Сначала реализуем метод ShowMessageBox. Во вкладке ClassViewвыберитеCMyObject->IMyObject->ShowMessageBox и напишите здесь следующий код:
_bstr_t temp(StringToWrite);
_bstr_t caption(m_Caption);
*Result=MessageBox(NULL,temp,caption,MB_YESNO|MB_ICONINFORMATION);
temp.~_bstr_t();
caption.~_bstr_t();
return S_OK;
Здесь вы видите переменную m_Caption, которую нам предстоит создать в будущем для связи свойства Caption и компонента, а также наверное незнакомый класс _bstr_t. _bstr_t предоставляет полезные операторы и методы для работы с типом BSTR, но чтобы его использовать вы должны подключить header comdef.h, откройте MyObject.h и после строки #include "resource.h" // main symbols добавьте #include "comdef.h". В этом коде MessageBox вернёт либо IDYES либо IDNO, в зависимости от того, на какую кнопку нажмёт пользователь, и это значение будет возвращать функция, т.к мы написали *Result=MessageBox..., а Result возвращаемый параметр. Возможно, тип long для Result был выбран неверно, т.к MessageBox возвращает числа от 1 до 9, но как я уже говорил, этот компонент - просто тест. Теперь осталось реализовать функции put_Caption и get_Caption. Чтобы это сделать, надо сначала добавить в класс CMyObject защищённую переменную m_Caption типа BSTR, её также не будет в интерфейсе, но она будет использоваться, чтобы хранить то значение, которое пользователь присвоит свойству Caption. Откройтефайл MyObject.h ипослестрок:
public:
STDMETHOD(get_Caption)(/*[out, retval]*/ BSTR *pVal);
STDMETHOD(put_Caption)(/*[in]*/ BSTR newVal);
STDMETHOD(ShowMessageBox)(/*[in]*/ const BSTR StringToWrite, /*[out,retval]*/ long *Result);
напишите:
protected:
BSTR m_Caption;
Здесь же в конструкторе класса напишите:
_bstr_t temp("Just a test!");
m_Caption=temp.copy();
temp.~_bstr_t();
Теперь переменная m_Caption инициализированна, по умолчанию в ней будет находиться строка "Just a test!". Ну а сейчас можно наконец-то заполнить функции get_Caption и put_Caption. Откройте файл MyObject.cpp, найдите там функцию get_Caption и напишите в ней:
*pVal=m_Caption;
return S_OK;
Теперь найдите функцию put_Caption и напишите в ней следующее:
m_Caption=newVal;
return S_OK;
Ну вот и всё в принципе, теперь можно компилировать компонент.
Другие работы по теме:
Завадостійке кодування на основі циклічних кодів
Microsoft Visual Studio Solution File, Format Version 10.00 # Visual Studio 2008 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CRC32", "CRC32CRC32.csproj", "{EE28F805-6DA0-4E7B-89A5-A3B245E1441D}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {EE28F805-6DA0-4E7B-89A5-A3B245E1441D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {EE28F805-6DA0-4E7B-89A5-A3B245E1441D}.Debug|Any CPU.Build.0 = Debug|Any CPU {EE28F805-6DA0-4E7B-89A5-A3B245E1441D}.Release|Any CPU.ActiveCfg = Release|Any CPU {EE28F805-6DA0-4E7B-89A5-A3B245E1441D}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE
Пример использования MFC в Visual C
В этой статье будет показано как включить потдержку MFC в Visual C++ на примере двух типов приложений: 1. Консольное приложение 2. Приложение типа Windows Application
Color Theory Essay Research Paper Color TheoryColor
Color Theory Essay, Research Paper Color Theory Color theory encompasses a multitude of definitions, concepts and design applications. All the information would fill several encyclopedias. As an introduction, here are a few basic concepts.
Light Matter Essay Research Paper Inner LightIn
Light Matter Essay, Research Paper Inner Light In order to understand what light is one has to understand how vision works. The process of visual perception is incredibly complex, involving many functions of the brain. In Arthur Zajonc’s book “Catching the Light,” he writes, “?vision requires far more than a functioning physical organ.
Memory Techniques Essay Research Paper Psychology 345Research
Memory Techniques Essay, Research Paper Psychology 345Research paperObjective: I will relate three memories from my experiences at Texas A&M University to three different memory techniques discussed in the book. One memory that I will remember occurred this semester. It involved a girl who was killed in a car accident.
Frege Against Idealism Essay Research Paper Frege
Frege Against Idealism Essay, Research Paper Frege vs. Idealism In a nut shell Idealism is the position that IDEAS, not objects, are the basis of reality. So for idealists the meaning of an expression is the idea associated with that expression. For example, if one were to think of a lamp , then under the idea theory of reference the visual image that we pull up would be the meaning of the expression lamp .
Visual Analysis Essay Research Paper A Tour
Visual Analysis Essay, Research Paper A Tour of the restaurantOn a casual day drive through Old Town Chicago, people may drive by a restaurant with a big sign with two large strange Chinese looking characters and on the bottom says Kamehachi. As one look more closely, the restaurant is pact with people. The valet parking is busy running around, and a line of people waiting to get in.
Musics Influence On People Essay Research Paper
Music is said to have a strong influence on how young impressionable minds live, think and act. However this can t be too much of a contreversy if tv. allows our minds not only be subject to the same ideas, but also it allows our young and innocent to have visual picture of what is going on. To the untrained this would seem like a crime, however this is just a process of growing up and we need to realize that kids will be kids and if we dont allow them to be explorative to what is going on in the world how will they ever be able to make rational grown decisions when their parents arent around?
Senseless A False Sense Of Perception Essay
, Research Paper Senseless: A False Sense of Perception I feel as though I have no choice but to be a skeptic about our ability to know the world on the sense experience given the information that is being
Convergence Of The Twain Essay Research Paper
“The Convergence of the Twain” Personification is “endowing inanimate objects or abstract ideas with life or human characteristics” (Kirszner 2058). In the poem “The Convergence of the Twain” the author?s use of personification allows the reader to make a more fluid transition from the past to the present.
Water Analysis Essay Research Paper Methods of
Water Analysis Essay, Research Paper Methods of Freshwater Analysis: Temperature pH Clarity Suspended Sediments Biotic Index Trent / BMWP Nitrate Level Phosphates Level Ammonia Concentration Visual Description Dissolved Oxygen Bacteria Counts Total Solids Chloride Concentration Iron Concentration Winkler Method of Oxygen Content 1.
Costa Sakellariou Essay Research Paper Costa Sakellariou
Costa Sakellariou Essay, Research Paper Costa Sakellariou Visual art can definitely be seen as a language. With every artist there is always some sort of meaning that they are trying to convey to the viewers of their work. The means of how they deliver that message is the language in which their work uses. In Costa Sakellariou?s work I especially felt there was some sort of language being spoken.
Learning Styles Essay Research Paper Every person
Learning Styles Essay, Research Paper Every person learns differently. From kindergartner to postgraduate levels, only students can do the earning, and they do it in their own particular, individual learning styles. Some children pick something up the first time they hear it. Others may not grasp a concept until they?ve had the chance to see it in print, or to write it themselves.
Learning Styles Compare
& Contrast Essay, Research Paper Learning Styles The purpose of this paper is to identify and compare the meaning as well as the differences of two learning styles as they relate to both the academic and professional realm. I have chosen these two styles because I believe the majority of people are either visual or auditory learners.
Tarzan Of The Apes Essay Research Paper
Tarzan of the Apes When I was reading the story, ?Tarzan of the Apes,? I realized that throughout the whole story he describes the characters very narrative. He describes specifically the characters feelings, movements and characteristics. On the following, I will write about how the author describes the characters to us readers and how it makes this story feel more realistic than what it is.
Visual Art Essay Research Paper VISUAL ARTS
Visual Art Essay, Research Paper VISUAL ARTS “The physical impossibility of death in the mind of someone living” By Damien Hirst (photo courtesy of the saatchi collection)
Visual Impairment Essay Research Paper Vision Impairments
Visual Impairment Essay, Research Paper Vision Impairments ” People catergorized as visually impaired range from individuals with mild visual losses to those with low vision to those who are totally blind” (Winzer,370). Vision impairments does not necessarily mean a total loss of sight. Some visually impaired person can detect light, others can see shapes and forms, and others can see nothing at all.
Presentation Skills Essay Research Paper Presentation SkillsEveryone
Presentation Skills Essay, Research Paper Presentation Skills Everyone knows the value of being able to communicate for a team project or the positive results of a well-written proposal. But in the area of Public Relations, you also need to be able to give an effective, professional presentation and in order to conquer this there are several things you should keep in mind.
Visual Perception Development Essay Research Paper Devlopment
Visual Perception Development Essay, Research Paper Devlopment of Visual Perception The development of visual perception changes through the caurse of life time from birth through adulthood. Sight is produced by taking ?stimulation in the form of light and converting it to electrochemical signals to the brain.? Most of the development of visual perception takes place in infants and then declines in old age.
Psychoology Essay Research Paper Visual sensation differs
Psychoology Essay, Research Paper Visual sensation differs from visual perception even though the two processes form a sequence. Our brain obtains meaning from what we look at through the process of sensation and perception (Grivas Down & Carter pg 77). Though the two systems interact they both serve a different purpose.
Dover Beach Essay Research Paper Dover Beachby
Dover Beach Essay, Research Paper ?Dover Beach? by: Matthew Arnold In the poem ?Dover Beach? by: Matthew Arnold there is a lot of irony, appeal to the auditory and visual sense, and illusions. The tone in this poem is very sad and dismal, but he shows us how to keep faith and hope in spite of that and how important being honest, true, and faithful to one another, really is.
The Masque Of The Red Death By 2
The Masque Of The Red Death By Edgar Allen Poe Essay, Research Paper Edgar Allen Poe’s ?The Masque of the Red Death? is an elaborate allegory that combines objects in the story with visual descriptions to give focus to the reader’s imagination. In the story, a prince named Prospero tries to dodge the Red Death through isolation and seclusion.
Masque Of The Red Death Essay Research
Paper The Masque of the Red Death: Language and Symbolism Edgar Allen Poe’s The Masque of the Red Death is an elaborate allegory that combines objects in the story with visual descriptions to give focus to the reader’s imagination. In the story,
Romeo Juliet- Comparison Between The Screenplay
And The 199 Essay, Research Paper Films are made with the directors different personal opinions based on the original screenplay. For the movie version of Romeo + Juliet (1996), the quote above illustrates this perfectly. For this essay, I will discuss contrasts between the original screenplay, and the film.
Television Essay Research Paper Televised debates between
Television Essay, Research Paper Televised debates between the nominees of the two major parties have become standard fare in contemporary presidential election campaigns. The authors of this important volume maintain that television has altered the very nature of presidential debates profoundly, that the demands of television have dictated the structure and formats of contemporary debates, and that the visual content of presidential debates plays an important role in the way that candidates exercise influence in televised debates.
Art 5 Essay Research Paper ArtArt comes
Art 5 Essay, Research Paper Art comes in many different forms. It isn t just visual work done on canvas using a certain medium, like pencils, watercolors, or oils. Art is just a way in which an individual expresses his or her inner most self, so that others can understand that individuals personality or feelings to their fullest.
Apple Picking Essay Research Paper Images of
Apple Picking Essay, Research Paper Images of Apple Picking Dr. Hofer "After Apple Picking" is fraught with imagery. Frost uses visual, olfactory, kinesthetic, tactile, and auditory imagery throughout this piece. Because the poem is filled with a variety of images, the reader is able to imagine the experience of apple picking.
What Are Visual Defects And How Common
Are They ? Essay, Research Paper What Are Visual Defects and How Common Are They ? Nate Schackow 2nd Period December 17, 1996 The human eye does alot more than allowing you to see. It is very
TV Violence Essay Research Paper Television ViolenceIn
TV Violence Essay, Research Paper Television Violence In today?s society, television violence harmfully affects the minds of children. However, it doesn?t mean that the violence on television is the only source for bad behavior, but it does largely contribute to the situation (Szaflik). For instance, the variety of television programming, which permeates violence, is sitcoms, commercials, and cartoons.
The Job Of A Graphic Designer Essay
, Research Paper Graphic designers create the visual presentation and design of goods, from gravestone markers to detergent boxes, from album covers to dog food cans (The Princeton Review Guide to Your Career.) Graphic artists, or graphic designers, are the bases of the graphic world. It is their designs that are sent to layout artists and then to the printers and then onto the outside world on cd covers, cereal boxes, billboards, posters, and basically anything that has to do with a visual representation.