Форум программистов, компьютерный форум, киберфорум
C++ Builder
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.78/9: Рейтинг темы: голосов - 9, средняя оценка - 4.78
говнокодер
 Аватар для sh4d°_°ff
1273 / 297 / 35
Регистрация: 31.10.2009
Сообщений: 1,432

Вставка картинки в RichEditOLE

04.12.2009, 20:25. Показов 1912. Ответов 3
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Уважаемые товарищи! проблема с картинками в RichEdit решена, но не до конца... Раз уж с буфером обмена накладки, тогда у меня появилась идея немного подредактировать
класс
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
//===========================================================================
// Copyright © 1998 Thin Air Enterprises and Robert Dunn
//===========================================================================
//---------------------------------------------------------------------------
// class TIRichEditOle - adds basic OLE functionality to TRichEdit.
// Based on code found at [url]http://www.dystopia.fi/~janij/techinfo/richedit.htm[/url]
// and presumably written by Jani Jдrvinen.  Thanks, Jani.
//
// Additional code developed through examination of Borland's VCL library,
// Microsoft's MFC source code, and sample code available on Microsoft's
// developer web site.
//
// Note that this code is very experimental -- the author admits to only a
// vague familiarity with OLE and accepts no criticism of the code.  Many,
// if not most, of the interfaces return failure codes arbitrarily chosen by
// the author with no particular reason to think that the values are correct.
// In particular, no great effort has been expended looking for "memory
// leaks," and these are considered quite probable.  You have been warned.
//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
 
#include "RichEditOLE.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
//---------------------------------------------------------------------------
// utiltiy functions
//---------------------------------------------------------------------------
//
static void OleUIMetafilePictIconFree(HGLOBAL hMetaPict)
{
    if (!hMetaPict) return;
 
    LPMETAFILEPICT pMF = (LPMETAFILEPICT) GlobalLock(hMetaPict);
 
    if (pMF && pMF->hMF) DeleteMetaFile(pMF->hMF);
    GlobalUnlock(hMetaPict);
    GlobalFree(hMetaPict);
    return;
}
 
static HRESULT OleStdSwitchDisplayAspect(LPOLEOBJECT  lpOleObj,
    LPDWORD lpdwCurAspect, DWORD dwNewAspect, HGLOBAL hMetaPict,
    BOOL fDeleteOldAspect, BOOL fSetupViewAdvise, LPADVISESINK lpAdviseSink,
    LPBOOL lpfMustUpdate)
{
    LPOLECACHE      lpOleCache = NULL;
    LPVIEWOBJECT    lpViewObj = NULL;
    LPENUMSTATDATA  lpEnumStatData = NULL;
    STATDATA        StatData;
    FORMATETC       FmtEtc;
    STGMEDIUM       Medium;
    DWORD           dwAdvf;
    DWORD           dwNewConnection;
    DWORD           dwOldAspect = *lpdwCurAspect;
    HRESULT         hrErr;
 
    if (lpfMustUpdate) *lpfMustUpdate = FALSE;
 
    lpOleObj->QueryInterface(IID_IOleCache, (LPVOID*)&lpOleCache);
 
    // if IOleCache* is NOT available, do nothing
    if (!lpOleCache) return E_INVALIDARG;
 
    // Setup new cache with the new aspect
    FmtEtc.cfFormat = 0;     // whatever is needed to draw
    FmtEtc.ptd      = NULL;
    FmtEtc.dwAspect = dwNewAspect;
    FmtEtc.lindex   = -1;
    FmtEtc.tymed    = TYMED_NULL;
 
    /* OLE2NOTE: if we are setting up Icon aspect with a custom icon
    **    then we do not want DataAdvise notifications to ever change
    **    the contents of the data cache. thus we set up a NODATA
    **    advise connection. otherwise we set up a standard DataAdvise
    **    connection.
    */
    if (dwNewAspect == DVASPECT_ICON && hMetaPict) dwAdvf = ADVF_NODATA;
    else dwAdvf = ADVF_PRIMEFIRST;
 
    hrErr = lpOleCache->Cache(&FmtEtc, dwAdvf, &dwNewConnection);
    if (!SUCCEEDED(hrErr)) {
        lpOleCache->Release();
        return hrErr;
        }
 
    *lpdwCurAspect = dwNewAspect;
 
    /* OLE2NOTE: if we are setting up Icon aspect with a custom icon,
    **    then stuff the icon into the cache. otherwise the cache must
    **    be forced to be updated. set the *lpfMustUpdate flag to tell
    **    caller to force the object to Run so that the cache will be
    **    updated.
    */
    if (dwNewAspect == DVASPECT_ICON && hMetaPict) {
        FmtEtc.cfFormat = CF_METAFILEPICT;
        FmtEtc.ptd      = NULL;
        FmtEtc.dwAspect = DVASPECT_ICON;
        FmtEtc.lindex   = -1;
        FmtEtc.tymed    = TYMED_MFPICT;
 
        Medium.tymed          = TYMED_MFPICT;
        Medium.hGlobal        = hMetaPict;
        Medium.pUnkForRelease = NULL;
 
        hrErr = lpOleCache->SetData(&FmtEtc, &Medium, FALSE /* fRelease */);
        }
    else if (lpfMustUpdate) *lpfMustUpdate = TRUE;
 
    if (fSetupViewAdvise && lpAdviseSink) {
        /* OLE2NOTE: re-establish the ViewAdvise connection */
        lpOleObj->QueryInterface(IID_IViewObject, (LPVOID*)&lpViewObj);
 
        if (lpViewObj) {
            lpViewObj->SetAdvise(dwNewAspect, 0, lpAdviseSink);
            lpViewObj->Release();
            }
        }
 
    /* OLE2NOTE: remove any existing caches that are set up for the old
    **    display aspect. It WOULD be possible to retain the caches set
    **    up for the old aspect, but this would increase the storage
    **    space required for the object and possibly require additional
    **    overhead to maintain the unused cachaes. For these reasons the
    **    strategy to delete the previous caches is prefered. If it is a
    **    requirement to quickly switch between Icon and Content
    **    display, then it would be better to keep both aspect caches.
    */
 
    if (fDeleteOldAspect) {
        hrErr = lpOleCache->EnumCache(&lpEnumStatData);
 
        while (hrErr == NOERROR) {
            hrErr = lpEnumStatData->Next(1, &StatData, NULL);
            if (hrErr != NOERROR) break;        // DONE! no more caches.
 
            if (StatData.formatetc.dwAspect == dwOldAspect)
                // Remove previous cache with old aspect
                lpOleCache->Uncache(StatData. dwConnection);
            }
 
        if (lpEnumStatData)
            if (lpEnumStatData->Release())
                throw EOleError("OleStdSwitchDisplayAspect: Cache enumerator NOT released");
        }
 
    if (lpOleCache) lpOleCache->Release();
 
    return NOERROR;
}
//---------------------------------------------------------------------------
// TIRichEditOle
//
TIRichEditOle::TIRichEditOle(TRichEdit* richedit) : FIRichEditOle(0)
{
    // do we need to call OleInitialize(NULL)? seems to work without it...
    ::OleInitialize(0);
 
    FIRichEditCallback = new TIRichEditOleCallback(richedit);
 
    FRichEdit = richedit;
    ::SendMessage(richedit->Handle, EM_SETOLECALLBACK, 0, (LPARAM) (LPRICHEDITOLECALLBACK) FIRichEditCallback);
    if (!::SendMessage(richedit->Handle, EM_GETOLEINTERFACE, 0, (LPARAM) &FIRichEditOle))
        FIRichEditOle = 0;
 
    // register clipboard formats used in ole (so we'll have the clipboard
    // format IDs for ole clipboard operations (like OleUIPasteSpecial)
    CFObjectDescriptor = RegisterClipboardFormat("Object Descriptor");
    CFEmbeddedObject = RegisterClipboardFormat("Embedded Object");
    CFLinkSource = RegisterClipboardFormat("Link Source");
    CFRtf = RegisterClipboardFormat(CF_RTF);
    CFRtfNoObjs = RegisterClipboardFormat(CF_RTFNOOBJS);
    CFReTextObjs = RegisterClipboardFormat(CF_RETEXTOBJ);
}
//---------------------------------------------------------------------------
TIRichEditOle::~TIRichEditOle(void)
{
    // close any active objects unconditionally
    if (FIRichEditOle) CloseActiveObjects(false);
 
    // set the callback to null
    ::SendMessage(FRichEdit->Handle, EM_SETOLECALLBACK, 0, (LPARAM) 0);
 
    // release the interface
    if (FIRichEditOle) {
        FIRichEditOle = 0;
        }
 
    if (FIRichEditCallback) {
        delete FIRichEditCallback;
        FIRichEditCallback = 0;
        }
 
    // balance calls to OleInitialize()
    OleUninitialize();
}
//---------------------------------------------------------------------------
void TIRichEditOle::SetHostNames(AnsiString hostApp, AnsiString hostDoc)
{
    if (!FIRichEditOle) return;
    FIRichEditOle->SetHostNames(hostApp.c_str(), hostDoc.c_str());
}
//---------------------------------------------------------------------------
LPOLECLIENTSITE TIRichEditOle::GetClientSite(void)
{
    LPOLECLIENTSITE clientSite;
    if (FIRichEditOle->GetClientSite(&clientSite) != S_OK) clientSite = 0;
    return clientSite;
}
//---------------------------------------------------------------------------
LONG TIRichEditOle::GetObjectCount(void)
{
    if (!FIRichEditOle) throw EOleError("IRichEditOle interface is not valid.");
    return FIRichEditOle->GetObjectCount();
}
//---------------------------------------------------------------------------
LONG TIRichEditOle::GetLinkCount(void)
{
    if (!FIRichEditOle) throw EOleError("IRichEditOle interface is not valid.");
    return FIRichEditOle->GetLinkCount();
}
//---------------------------------------------------------------------------
bool TIRichEditOle::InsertObject(void)
{
    LPOLEOBJECT pOleObject = 0;
 
    // better be a valid richedit
    if (!FRichEdit) return false;
 
    // make sure client site is valid
    LPOLECLIENTSITE pClientSite = GetClientSite();
    if (!pClientSite) throw EOleError("IOleClientSite interface is not valid.");
 
    // get substorage
    LPSTORAGE pStg;
    if (FIRichEditCallback->GetNewStorage(&pStg) != S_OK) {
        pClientSite->Release();
        throw EOleError("GetNewStorage failed.");
        }
 
    // display the InsertObject dialog
    TCHAR buf[MAX_PATH];
    buf[0] = 0;
    OLEUIINSERTOBJECT io;
 
    ::memset(&io, 0, sizeof(io));
    io.cbStruct = sizeof(io);
    io.dwFlags = IOF_SHOWHELP | IOF_CREATENEWOBJECT | IOF_CREATEFILEOBJECT |
        IOF_SELECTCREATENEW | IOF_CREATELINKOBJECT;
    io.hWndOwner = Application->MainForm->Handle;
    io.lpszFile = buf;
    io.cchFile = sizeof(buf);
    io.iid = IID_IOleObject;
    io.oleRender = OLERENDER_DRAW;
    io.lpIOleClientSite = pClientSite;
    io.lpIStorage = pStg;
    io.ppvObj = (void**) &pOleObject;
    io.clsid = CLSID_NULL;
 
    DWORD retVal = ::OleUIInsertObject(&io);
    if (retVal != OLEUI_SUCCESS) {
        pClientSite->Release();
        pStg->Release();
        if (io.hMetaPict) ::OleUIMetafilePictIconFree(io.hMetaPict);
        if (pOleObject) pOleObject->Release();
        if (retVal == OLEUI_CANCEL) return false;
        throw EOleError("Insert Object dialog returned failure.");
        }
 
    // got the object
    pOleObject = (LPOLEOBJECT) *io.ppvObj;
 
    REOBJECT reObj;
    ::memset(&reObj, 0, sizeof(reObj));
    reObj.cbStruct = sizeof(reObj);
    reObj.cp = REO_CP_SELECTION;
    reObj.clsid = io.clsid;
    reObj.poleobj = pOleObject;
    reObj.pstg = pStg;
    reObj.polesite = pClientSite;
    reObj.dvaspect = DVASPECT_CONTENT;
    reObj.dwFlags = REO_RESIZABLE;
 
    if (io.dwFlags & IOF_SELECTCREATENEW) reObj.dwFlags |= REO_BLANK;
 
    // try to get a valid clsid
    if (::IsEqualCLSID(reObj.clsid, CLSID_NULL)) {
#ifdef UNICODE
        ::GetClassFile(buf, &reObj.clsid);
#else
        WCHAR bufFile[MAX_PATH];
        ::MultiByteToWideChar(CP_ACP, 0, buf, -1, bufFile, sizeof(bufFile));
        ::GetClassFile(bufFile, &reObj.clsid);
#endif
        }
 
    // display as icon?
    if (io.dwFlags & IOF_CHECKDISPLAYASICON) {
        int fUpdate;
        if (::OleStdSwitchDisplayAspect(pOleObject, &reObj.dvaspect,
            DVASPECT_ICON, io.hMetaPict, true, false, 0, &fUpdate))
            Application->MessageBox("Cannot display object as icon.",
                "Insert Object", MB_OK | MB_ICONWARNING);
        }
 
    // insert the object into the richedit
    if (FIRichEditOle->InsertObject(&reObj) != S_OK) {
        pClientSite->Release();
        pStg->Release();
        if (io.hMetaPict) OleUIMetafilePictIconFree(io.hMetaPict);
        if (pOleObject) pOleObject->Release();
        throw EOleError("RichEdit refused to insert object.");
        }
 
    // if new object, do the show verb
    if (io.dwFlags & IOF_SELECTCREATENEW) {
        // get object position
        POINT pt;
        // hey! where is REO_IOB_SELECTION documented!
        ::SendMessage(FRichEdit->Handle, EM_POSFROMCHAR, (WPARAM) &pt, REO_IOB_SELECTION);
        RECT rect = { 0, 0, 100, 100 };
        ::OffsetRect(&rect, pt.x, pt.y);
        pOleObject->DoVerb(OLEIVERB_SHOW, 0, pClientSite, 0, FRichEdit->Handle, &rect);
        }
 
    pClientSite->Release();
    pStg->Release();
    if (io.hMetaPict) OleUIMetafilePictIconFree(io.hMetaPict);
    if (pOleObject) pOleObject->Release();
 
    return true;
}
//---------------------------------------------------------------------------
bool TIRichEditOle::PasteSpecial(void)
{
    TOleUIPasteSpecial data;
    TOleUIPasteEntry formats[8];
 
    ::memset(&data, 0, sizeof(data));
    ::memset(&formats, 0, sizeof(formats));
 
    data.cbStruct = sizeof(data);
    data.hWndOwner = Application->MainForm->Handle;
    data.arrPasteEntries = formats;
    data.cPasteEntries = sizeof(formats) / sizeof(formats[0]);
    data.arrLinkTypes = &CFLinkSource;
    data.cLinkTypes = 1;
 
    // the following entries were devined from MS MFC code and appear to
    // be fairly standard for rich edit controls; this is basically a static
    // table and could be moved, but the overhead here is small...
    formats[0].fmtetc.cfFormat = (CLIPFORMAT) CFEmbeddedObject;
    formats[0].fmtetc.dwAspect = DVASPECT_CONTENT;
    formats[0].fmtetc.lindex = -1;
    formats[0].fmtetc.tymed = TYMED_ISTORAGE;
    formats[0].lpstrFormatName = "%s";
    formats[0].lpstrResultText = "%s";
    formats[0].dwFlags = OLEUIPASTE_PASTE | OLEUIPASTE_ENABLEICON;
 
    formats[1].fmtetc.cfFormat = (CLIPFORMAT) CFLinkSource;
    formats[1].fmtetc.dwAspect = DVASPECT_CONTENT;
    formats[1].fmtetc.lindex = -1;
    formats[1].fmtetc.tymed = TYMED_ISTREAM;
    formats[1].lpstrFormatName = "%s";
    formats[1].lpstrResultText = "%s";
    formats[1].dwFlags = OLEUIPASTE_LINKTYPE1 | OLEUIPASTE_ENABLEICON;
 
    formats[2].fmtetc.cfFormat = CF_TEXT;
    formats[2].fmtetc.dwAspect = DVASPECT_CONTENT;
    formats[2].fmtetc.lindex = -1;
    formats[2].fmtetc.tymed = TYMED_HGLOBAL;
    formats[2].lpstrFormatName = "Unformatted Text";
    formats[2].lpstrResultText = "text without any formatting";
    formats[2].dwFlags = OLEUIPASTE_PASTEONLY;
 
    formats[3].fmtetc.cfFormat = (CLIPFORMAT) CFRtf;
    formats[3].fmtetc.dwAspect = DVASPECT_CONTENT;
    formats[3].fmtetc.lindex = -1;
    formats[3].fmtetc.tymed = TYMED_HGLOBAL;
    formats[3].lpstrFormatName = "Formatted Text (RTF)";
    formats[3].lpstrResultText = "text with font and paragraph formatting";
    formats[3].dwFlags = OLEUIPASTE_PASTEONLY;
 
    formats[4].fmtetc.cfFormat = CF_ENHMETAFILE;
    formats[4].fmtetc.dwAspect = DVASPECT_CONTENT;
    formats[4].fmtetc.lindex = -1;
    formats[4].fmtetc.tymed = TYMED_ENHMF;
    formats[4].lpstrFormatName = "Picture (Enhanced Metafile)";
    formats[4].lpstrResultText = "a picture";
    formats[4].dwFlags = OLEUIPASTE_PASTEONLY;
 
    formats[5].fmtetc.cfFormat = CF_METAFILEPICT;
    formats[5].fmtetc.dwAspect = DVASPECT_CONTENT;
    formats[5].fmtetc.lindex = -1;
    formats[5].fmtetc.tymed = TYMED_MFPICT;
    formats[5].lpstrFormatName = "Picture (Metafile)";
    formats[5].lpstrResultText = "a picture";
    formats[5].dwFlags = OLEUIPASTE_PASTEONLY;
 
    formats[6].fmtetc.cfFormat = CF_DIB;
    formats[6].fmtetc.dwAspect = DVASPECT_CONTENT;
    formats[6].fmtetc.lindex = -1;
    formats[6].fmtetc.tymed = TYMED_MFPICT;
    formats[6].lpstrFormatName = "Device Independent Bitmap";
    formats[6].lpstrResultText = "a device independent bitmap";
    formats[6].dwFlags = OLEUIPASTE_PASTEONLY;
 
    formats[7].fmtetc.cfFormat = CF_BITMAP;
    formats[7].fmtetc.dwAspect = DVASPECT_CONTENT;
    formats[7].fmtetc.lindex = -1;
    formats[7].fmtetc.tymed = TYMED_GDI;
    formats[7].lpstrFormatName = "Bitmap";
    formats[7].lpstrResultText = "a bitmap";
    formats[7].dwFlags = OLEUIPASTE_PASTEONLY;
 
    DWORD retVal = OleUIPasteSpecial(&data);
    if (retVal == OLEUI_OK) {
        // apparently, richedit handles linking for us; unfortunately, some
        // objects do not embed (MS Word/Office 97 simply fails to embed,
        // although linking works...
        if (FIRichEditOle->ImportDataObject(data.lpSrcDataObj,
            formats[data.nSelectedIndex].fmtetc.cfFormat,
            (data.dwFlags & PSF_CHECKDISPLAYASICON) ? data.hMetaPict : 0) != S_OK)
            throw EOleError("RichEdit refused to paste object.");
      }
 
    if (data.hMetaPict) OleUIMetafilePictIconFree(data.hMetaPict);
    if (data.lpSrcDataObj) data.lpSrcDataObj->Release();
    return retVal == OLEUI_OK;
}
//---------------------------------------------------------------------------
// close any active ole objects (else servers left hanging); return false on
// cancel unconditionally if savePrompt != true (changes are lost)
//
bool TIRichEditOle::CloseActiveObjects(bool savePrompt)
{
    // if no interface, yell
    if (!FIRichEditOle) throw EOleError("RichEdit OLE interface is not valid.");
 
    // get the total number of objects
    int objCnt = FIRichEditOle->GetObjectCount();
 
    // check each object and, if active, deactivate and, if open, close
    for (int i = 0; i < objCnt; i++) {
        REOBJECT reObj;
        ::memset(&reObj, 0, sizeof(reObj));
        reObj.cbStruct = sizeof(reObj);
 
        // get object data
        if (FIRichEditOle->GetObject(i, &reObj, REO_GETOBJ_POLEOBJ) == S_OK) {
            // if active, kill it
            if (reObj.dwFlags & REO_INPLACEACTIVE)
                FIRichEditOle->InPlaceDeactivate();
            // if open, close it (prompting if requested)
            HRESULT hr = S_OK;
            if (reObj.dwFlags & REO_OPEN)
                hr = reObj.poleobj->Close(savePrompt ?
                    OLECLOSE_PROMPTSAVE : OLECLOSE_NOSAVE);
            // release the interface
            reObj.poleobj->Release();
            // if cancelled, return false
            if (hr == OLE_E_PROMPTSAVECANCELLED) return false;
            }
        }
 
    return true;
}
//===========================================================================
// Copyright © 1998 Thin Air Enterprises and Robert Dunn
//===========================================================================
, который используется при вставке изображения.

собственно есть мысль, что можно его дополнить функцией аналогичной InsertObject(), только измененной. Т.е.:например в функцию у нас идет например AnsiString с именем файла или Bitmap... и соответственно потом идет их отображение в RichEditе. Оригинальная функция InsertObject() вызывает диалог аналогичный OleContainer->InsertObjectDialog() затем вставка;

мои исследования функции привели к тому что после выбора в диалоге файла, его адрес заносится сюда:

C++
1
io.lpszFile = buf; //(строка №252)
но как я это не крутил, ничего достойного называться результатом я не добился. К сожалению, данная задача еще слишком сложна для меня (мало опыта в подобной работе).. поэтому буду рад любой оказанной помощи.

з.ы.: Конечно можете сказать что иди мол купи RichView... сразу говорю - для меня - не вариант.
0
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
04.12.2009, 20:25
Ответы с готовыми решениями:

Вставка картинки в фигуру
Как залить эллипс круглой картинкой? то есть у меня то получается залить, но заливает со сдвигом изображения, мозаикой, а мне жизненно...

Вставка картинки из Canvas в Word
Всем доброго времени суток. Подскажите как в документ Word вставить картинку? Текст вставляю вот...

вставка BMP картинки и её движение
Здравствуйте! У меня есть задание реализовать детскую игрушку. Написать программу нужно объктно-ориентированным способом. Я взяла машинку....

3
говнокодер
 Аватар для sh4d°_°ff
1273 / 297 / 35
Регистрация: 31.10.2009
Сообщений: 1,432
07.12.2009, 21:29  [ТС]
Уважаемые... неужели никому неинтересен вопрос?... никаких мыслей... мне кажется дело все-таки общее...
вот еще куда дошли мои глаза... правда толку от этого немного...
сама вставка картинки (в моем случае из буфера обмена) "выполняется" в
RichEditOleCallback

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
//===========================================================================
// Copyright © 1998 Thin Air Enterprises and Robert Dunn
//===========================================================================
//---------------------------------------------------------------------------
// class TIRichEditOle - adds basic OLE functionality to TRichEdit.
// Based on code found at [url]http://www.dystopia.fi/~janij/techinfo/richedit.htm[/url]
// and presumably written by Jani Järvinen.  Thanks, Jani.
//
// Additional code developed through examination of Borland's VCL library,
// Microsoft's MFC source code, and sample code available on Microsoft's
// developer web site.
//
// Note that this code is very experimental -- the author admits to only a
// vague familiarity with OLE and accepts no criticism of the code.  Many,
// if not most, of the interfaces return failure codes arbitrarily chosen by
// the author with no particular reason to think that the values are correct.
// In particular, no great effort has been expended looking for "memory
// leaks," and these are considered quite probable.  You have been warned.
//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
 
#include "RichEditOleCallback.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
//---------------------------------------------------------------------------
TIRichEditOleCallback::TIRichEditOleCallback(TRichEdit* richedit) : FRefCnt(0)
{
    FRichEdit = richedit;
    FAcceptDrop = false;
}
//---------------------------------------------------------------------------
TIRichEditOleCallback::~TIRichEditOleCallback(void)
{
}
//---------------------------------------------------------------------------
STDMETHODIMP TIRichEditOleCallback::QueryInterface(THIS_ REFIID riid,
    LPVOID FAR * lplpObj)
{
    // return S_OK if the interface is supported, E_NOINTERFACE if not.
    if (riid == IID_IUnknown)
        *lplpObj = (LPUNKNOWN) this;
    else if (riid == IID_IRichEditOleCallback)
        *lplpObj = (LPRICHEDITOLECALLBACK) this;
    else {
        *lplpObj = 0;
        return E_NOINTERFACE;
        }
 
    ((LPUNKNOWN) *lplpObj)->AddRef();
    return S_OK;
}
//---------------------------------------------------------------------------
STDMETHODIMP_(ULONG) TIRichEditOleCallback::AddRef(THIS)
{
    // need to add real reference counting if any caller really holds
    // on to interface pointers
    return ++FRefCnt;
}
//---------------------------------------------------------------------------
STDMETHODIMP_(ULONG) TIRichEditOleCallback::Release(THIS)
{
    // need to add real reference counting if any caller really holds
    // on to interface pointers
    --FRefCnt;
    return FRefCnt;
}
//---------------------------------------------------------------------------
// *** IRichEditOleCallback methods ***
STDMETHODIMP TIRichEditOleCallback::GetNewStorage(THIS_ LPSTORAGE FAR * lplpstg)
{
    if (!lplpstg) return E_INVALIDARG;   //3
    *lplpstg = NULL;           //4
 
    //
    // We need to create a new storage for an object to occupy.  We're going
    // to do this the easy way and just create a storage on an HGLOBAL and let
    // OLE do the management.  When it comes to saving things we'll just let
    // the RichEdit control do the work.  Keep in mind this is not efficient.
    //
    LPLOCKBYTES pLockBytes;
    HRESULT hr = ::CreateILockBytesOnHGlobal(NULL, TRUE, &pLockBytes);  //5
    if (FAILED(hr)) return hr;       //6
 
    hr = ::StgCreateDocfileOnILockBytes(pLockBytes,       //7
        STGM_SHARE_EXCLUSIVE | STGM_CREATE | STGM_READWRITE, 0, lplpstg);
    pLockBytes->Release();       //8
    return hr;          //9
}
//---------------------------------------------------------------------------
STDMETHODIMP TIRichEditOleCallback::GetInPlaceContext(THIS_ LPOLEINPLACEFRAME FAR * lplpFrame,
    LPOLEINPLACEUIWINDOW FAR * lplpDoc, LPOLEINPLACEFRAMEINFO lpFrameInfo)
{
    return E_NOTIMPL;   // what to return???
}
//---------------------------------------------------------------------------
STDMETHODIMP TIRichEditOleCallback::ShowContainerUI(THIS_ BOOL fShow)
{
    return E_NOTIMPL;   // what to return???
}
//---------------------------------------------------------------------------
STDMETHODIMP TIRichEditOleCallback::QueryInsertObject(THIS_ LPCLSID lpclsid,
    LPSTORAGE lpstg, LONG cp)
{
    // let richedit insert any and all objects
    return S_OK;        // 10
}
//---------------------------------------------------------------------------
STDMETHODIMP TIRichEditOleCallback::DeleteObject(THIS_ LPOLEOBJECT lpoleobj)
{
    // per doc, no return value, i.e., this is simply a notification
    return S_OK;
}
//---------------------------------------------------------------------------
STDMETHODIMP TIRichEditOleCallback::QueryAcceptData(THIS_ LPDATAOBJECT lpdataobj,
    CLIPFORMAT FAR * lpcfFormat, DWORD reco, BOOL fReally, HGLOBAL hMetaPict)
{
    // allow insertion on dropped file?
    if (reco == RECO_DROP && !FAcceptDrop) return E_NOTIMPL;    //1
    return S_OK;         //2
}
//---------------------------------------------------------------------------
STDMETHODIMP TIRichEditOleCallback::ContextSensitiveHelp(THIS_ BOOL fEnterMode)
{
    return E_NOTIMPL;   // what to return???
}
//---------------------------------------------------------------------------
STDMETHODIMP TIRichEditOleCallback::GetClipboardData(THIS_ CHARRANGE FAR * lpchrg,
    DWORD reco, LPDATAOBJECT FAR * lplpdataobj)
{
    return E_NOTIMPL;   // what to return???
}
//---------------------------------------------------------------------------
STDMETHODIMP TIRichEditOleCallback::GetDragDropEffect(THIS_ BOOL fDrag,
    DWORD grfKeyState, LPDWORD pdwEffect)
{
    // per doc, no return value, i.e., for notification only
    *pdwEffect = DROPEFFECT_NONE;
    return S_OK;
}
//---------------------------------------------------------------------------
STDMETHODIMP TIRichEditOleCallback::GetContextMenu(THIS_ WORD seltype,
    LPOLEOBJECT lpoleobj, CHARRANGE FAR * lpchrg, HMENU FAR * lphmenu)
{
    return E_NOTIMPL;   // what to return???
}
//===========================================================================
// Copyright © 1998 Thin Air Enterprises and Robert Dunn
//===========================================================================

причем в определенном порядке (порядок я отметил в комментариях, всего 10 точек)
1
UeArtemis
18 / 18 / 3
Регистрация: 23.09.2011
Сообщений: 205
14.06.2016, 16:35
http://www.codeproject.com/Art... s-and-Othe
Тут проблему решили, но для VC6. Как бы переложить на наш Builder.

Добавлено через 28 минут
А, не сразу понял, что речь о вставке из буфера.
Тогда, возможно, это поможет: http://www.codeguru.com/cpp/co... ontrol.htm
0
UeArtemis
18 / 18 / 3
Регистрация: 23.09.2011
Сообщений: 205
22.06.2016, 14:57
Через буфер прекрасно вставляется, если подключить те файлы. Спасибо за них, кстати.
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
        //В метафайл
        TMetafile *MF = new TMetafile();
        MF->Inch=MyForm->PixelsPerInch;
        MF->MMWidth=254*ImageFon->Picture->Width/MF->Inch;
        MF->MMHeight=254*ImageFon->Picture->Height/MF->Inch;
        MF->SetSize(ImageFon->Width*1.1, ImageFon->Height*1.1);
        TMetafileCanvas *tMetaCanv = new TMetafileCanvas(MF,0);
        //Рисуем на канве что-нибудь
        delete tMetaCanv;//Удалять до загрузки в поток/файл!
        OpenClipboard(this->Handle);
        EmptyClipboard();
        SetClipboardData(CF_ENHMETAFILE, (HENHMETAFILE) MF->Handle);
        CloseClipboard();
        delete MF;
        RichEdit1->PasteFromClipboard();
А вот напрямую набросать в RTF-файл пока не удаётся. В буфере происходит какое-то преобразование: картинки сохранённые вручную в документ путём вписывания байтов "в хексе" отличаются от тех, что вписывает программа сама из буфера. У преобразованных в буфере есть дополнительные байты в начале и конце. Это в этих "шапке" и "хвосте" я пока не выяснил.
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
22.06.2016, 14:57
Помогаю со студенческими работами здесь

Вставка картинки в базу SQL запросом
Доброе время суток! Не получается вставить картинку в БД Paradox7 Bd-&gt;Query1-&gt;Close(); ...

Изменение почтового шаблона, вставка графики в письмо (типа логотипа) + вставка картинки в шаблоне
Здравствуйте) Возникло 2 вопроса. 1)Хочется сделать красивый почтовый шаблон с использованием графики. Возможно ли сделать это...

вставка картинки
Помогите пожалуйста. Нужно вставить картинку в эту область del вот код &lt;HTML&gt; &lt;head&gt; &lt;meta...

Вставка картинки
В общем по изменению числа необходимо чтобы менялась картинка,(я написал, но на цвет). Помогите... case 1: pictureBox1.BackColor =...

Вставка картинки
Как вставить картинку в форму?


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
4
Ответ Создать тему
Новые блоги и статьи
Настройки VS Code
Loafer 13.04.2026
{ "cmake. configureOnOpen": false, "diffEditor. ignoreTrimWhitespace": true, "editor. guides. bracketPairs": "active", "extensions. ignoreRecommendations": true, . . .
Оптимизация кода на разграничение прав доступа к элементам формы
Maks 13.04.2026
Алгоритм из решения ниже реализован на нетиповом документе, разработанного в конфигурации КА2. Задачи, как таковой, поставлено не было, проделанное ниже исключительно моя инициатива. Было так:. . .
Контроль заполнения и очистка дат в зависимости от значения перечислений
Maks 12.04.2026
Алгоритм из решения ниже реализован на примере нетипового документа "ПланированиеПерсонала", разработанного в конфигурации КА2. Задача: реализовать контроль корректности заполнения дат назначения. . .
Архитектура слоя интернета для сервера-слоя.
Hrethgir 11.04.2026
В продолжение https:/ / www. cyberforum. ru/ blogs/ 223907/ 10860. html Знаешь что я подумал? Раз мы все источники пишем в голове ветки, то ничего не мешает добавить в голову такой источник, который сам. . .
Подстановка значения реквизита справочника в табличную часть документа
Maks 10.04.2026
Алгоритм из решения ниже реализован на примере нетипового документа "ПланированиеПерсонала", разработанного в конфигурации КА2. Задача: при выборе сотрудника (справочник Сотрудники) в ТЧ документа. . .
Очистка реквизитов документа при копировании
Maks 09.04.2026
Алгоритм из решения ниже применим как для типовых, так и для нетиповых документов на самых различных конфигурациях. Задача: при копировании документа очищать определенные реквизиты и табличную. . .
модель ЗдравоСохранения 8. Подготовка к разному выполнению заданий
anaschu 08.04.2026
https:/ / github. com/ shumilovas/ med2. git main ветка * содержимое блока дэлэй из старой модели теперь внутри зайца новой модели 8ATzM_2aurI
Блокировка документа от изменений, если он открыт у другого пользователя
Maks 08.04.2026
Алгоритм из решения ниже реализован на примере нетипового документа, разработанного в конфигурации КА2. Задача: запретить редактирование документа, если он открыт у другого пользователя. / / . . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru