void __fastcall TMainForm::GetBtnClick(TObject *Sender)
{
TFileStream* fs;
int ReadByte=0;
int ReadBlock=0;
int NewReadBlock=ReadBlockEd->Text.ToInt();
bool Done=false;
String File=FileEd->Text;
String URL = URLEd->Text;
IdHTTP1->Request->ProxyPassword = PasswordEd->Text;
IdHTTP1->Request->ProxyServer = "ps.proxy.ru";
IdHTTP1->Request->ProxyPort = 3128;
IdHTTP1->Request->ProxyUsername = UserEd->Text;
//если файл ранее уже закачивался...
if(ini->SectionExists(URL)) {
ReadByte = ini->ReadInteger(URL, "ReadByte", 0);
Done = ini->ReadBool(URL, "Done", true);
if(Done) {
ShowMessage(String("Файл закачен полностью. Размер - ") + ReadByte + String(" байт."));
return;
}
ReadBlock = ini->ReadInteger(URL, "ReadBlock", 0);
ReadBlock = (ReadBlock == NewReadBlock)? ReadBlock:NewReadBlock;
File = ini->ReadString(URL, "File", 0);
TFileStream* fs = new TFileStream(File, fmOpenWrite);
fs->Position = ReadByte;
IdHTTP1->Request->ContentRangeStart = ReadByte;
IdHTTP1->Request->ContentRangeEnd = ReadByte + ReadBlock;
IdHTTP1->Get(URL, fs);
if(IdHTTP1->Request->ContentRangeEnd > IdHTTP1->Response->ContentRangeEnd) {
ini->WriteInteger(URL, "ReadByte", IdHTTP1->Response->ContentLength + IdHTTP1->Response->ContentRangeStart);
ini->WriteInteger(URL, "ReadBlock", ReadBlock);
//ini->WriteString(URL, "File", File);
ini->WriteInteger(URL, "Done", true);
}
else {
ini->WriteInteger(URL, "ReadByte", ReadByte + ReadBlock);
ini->WriteInteger(URL, "ReadBlock", ReadBlock);
//ini->WriteString(URL, "File", File);
ini->WriteInteger(URL, "Done", false);
}
delete fs;
}
else {
TFileStream* fs = new TFileStream(File, fmCreate);
fs->Position = ReadByte;
IdHTTP1->Request->ContentRangeStart = ReadByte;
IdHTTP1->Request->ContentRangeEnd = ReadByte + NewReadBlock;
IdHTTP1->Get(URL, fs);
if(IdHTTP1->Request->ContentRangeEnd > IdHTTP1->Response->ContentRangeEnd) {
ini->WriteInteger(URL, "ReadByte", IdHTTP1->Response->ContentLength + IdHTTP1->Response->ContentRangeStart);
ini->WriteInteger(URL, "ReadBlock", NewReadBlock);
ini->WriteString(URL, "File", File);
ini->WriteInteger(URL, "Done", true);
}
else {
ini->WriteInteger(URL, "ReadByte", ReadByte + NewReadBlock);
ini->WriteInteger(URL, "ReadBlock", NewReadBlock);
ini->WriteString(URL, "File", File);
ini->WriteInteger(URL, "Done", false);
}
delete fs;
}
}
Сетевое программирование и Интернет
Здесь вопросы по Интернет (сети, протоколы и т.д.)
Как скачать файл из Инета?
Ответ
Вариант 1.
Можно возпользоваться компонентом TIdHTTP с вкладки Indy. Данные компоненты входят в поставку BCB начиная с версии 6.0. Для более ранних версий BCB их можно скачать с оффсайта разработчика: INDY
Пример:
Код:
Вариант 2.
Воспользоваться функциями WinInet. Необходимо включить хедер wininet.h и подключить к проекту файл $(BCB)\LIB\PSDK\wininet.lib
Пример:
Код:
void __fastcall TForm1::Button1Click(TObject *Sender)
{
char szUrl[] = "http://www.codenet.ru";
//String Page;
HINTERNET hInternet = InternetOpen("MY AGENT",
INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
HINTERNET hRequest = InternetOpenUrl(hInternet, szUrl, NULL, 0, 0, 0);
if(hRequest)
{
DWORD dwRead;
char szTemp[1024];
TFileStream* fs = new TFileStream(ExtractFilePath(Application->ExeName) + "\\Page.html", fmCreate);
while (InternetReadFile(hRequest, (LPVOID)szTemp, 1024, &dwRead))
{
if (!dwRead) break;
fs->Write(szTemp, dwRead);
//Page = Page + String(szTemp);
}
delete fs;
}
InternetCloseHandle(hRequest);
InternetCloseHandle(hInternet);
}
{
char szUrl[] = "http://www.codenet.ru";
//String Page;
HINTERNET hInternet = InternetOpen("MY AGENT",
INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
HINTERNET hRequest = InternetOpenUrl(hInternet, szUrl, NULL, 0, 0, 0);
if(hRequest)
{
DWORD dwRead;
char szTemp[1024];
TFileStream* fs = new TFileStream(ExtractFilePath(Application->ExeName) + "\\Page.html", fmCreate);
while (InternetReadFile(hRequest, (LPVOID)szTemp, 1024, &dwRead))
{
if (!dwRead) break;
fs->Write(szTemp, dwRead);
//Page = Page + String(szTemp);
}
delete fs;
}
InternetCloseHandle(hRequest);
InternetCloseHandle(hInternet);
}
Вариант 3.
Непосредственно юзать WinSock API. Например скачиваем страницу и помещаем ее содержимое в Memo.
Пример:
Код:
//Winsock API
char request[]=
"GET / HTTP/1.0\r\n\
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*\r\n\
Accept-Language: ru\r\n\
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.1.4322)\r\n\
Host: www.codenet.ru\r\n\r\n";
#define MAX_PACKET_SIZE 4096
void __fastcall TForm1::Button3Click(TObject *Sender)
{
WSADATA ws;
SOCKET s;
sockaddr_in adr;
hostent* hn;
char buff [MAX_PACKET_SIZE];
// Init
if (WSAStartup (0x0101, &ws) != 0)
{
// Error
return;
}
// Создаем сокет
if (INVALID_SOCKET == (s = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP) ) )
{
// Error
return;
}
// получаем ИП
if (NULL == ( hn = gethostbyname ("www.codenet.ru") ) )
{
// Error
return;
}
// Заполгняем структуру
adr.sin_family = AF_INET;
adr.sin_addr.S_un.S_addr = *(DWORD* ) hn->h_addr_list[0];
adr.sin_port = htons (80);
// Устанавливаем соединение
if (SOCKET_ERROR == connect (s, (sockaddr* )&adr, sizeof (adr) ) )
{
// Error
return;
}
// Посылаем запрос
if (SOCKET_ERROR == send (s, request, strlen(request), 0) )
{
// Error
return;
}
// Принимаем данные
int len;
do
{
if (SOCKET_ERROR == (len = recv (s, (char *) &buff, MAX_PACKET_SIZE, 0) ) )
return;
Memo1->Lines->Add(buff);
}
while (len!=0);
/*int len = recv (s, (char *) &buff, MAX_PACKET_SIZE, 0);
if ( (len == SOCKET_ERROR) || (len == 0) )
{
// Error
return ;
}
// Выводим полученное
Memo1->Lines->Add(buff);*/
// Cae?uaaai niaaeiaiea
if (SOCKET_ERROR == closesocket (s) )
{
// Error
return ;
}
}
char request[]=
"GET / HTTP/1.0\r\n\
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*\r\n\
Accept-Language: ru\r\n\
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.1.4322)\r\n\
Host: www.codenet.ru\r\n\r\n";
#define MAX_PACKET_SIZE 4096
void __fastcall TForm1::Button3Click(TObject *Sender)
{
WSADATA ws;
SOCKET s;
sockaddr_in adr;
hostent* hn;
char buff [MAX_PACKET_SIZE];
// Init
if (WSAStartup (0x0101, &ws) != 0)
{
// Error
return;
}
// Создаем сокет
if (INVALID_SOCKET == (s = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP) ) )
{
// Error
return;
}
// получаем ИП
if (NULL == ( hn = gethostbyname ("www.codenet.ru") ) )
{
// Error
return;
}
// Заполгняем структуру
adr.sin_family = AF_INET;
adr.sin_addr.S_un.S_addr = *(DWORD* ) hn->h_addr_list[0];
adr.sin_port = htons (80);
// Устанавливаем соединение
if (SOCKET_ERROR == connect (s, (sockaddr* )&adr, sizeof (adr) ) )
{
// Error
return;
}
// Посылаем запрос
if (SOCKET_ERROR == send (s, request, strlen(request), 0) )
{
// Error
return;
}
// Принимаем данные
int len;
do
{
if (SOCKET_ERROR == (len = recv (s, (char *) &buff, MAX_PACKET_SIZE, 0) ) )
return;
Memo1->Lines->Add(buff);
}
while (len!=0);
/*int len = recv (s, (char *) &buff, MAX_PACKET_SIZE, 0);
if ( (len == SOCKET_ERROR) || (len == 0) )
{
// Error
return ;
}
// Выводим полученное
Memo1->Lines->Add(buff);*/
// Cae?uaaai niaaeiaiea
if (SOCKET_ERROR == closesocket (s) )
{
// Error
return ;
}
}
Вариант 4.
Воспользоваться ф-ией URLDownloadToFile. Необходимо включить хедер urlmon.h и подключить к проекту файл $(BCB)\LIB\PSDK\urlmon.lib
Пример:
Код:
URLDownloadToFile( 0, "http://www.codenet.ru", "c:\\temp\myfile.html", 0, 0);
Автор ответа: ***
Как для CppWebBrowser запретить(изменить) вывод стандартного контекстного меню?
Ответ
Реализуйте собственный интерфейс IDocHostUIHandler (главным образом его метод ShowContextMenu в нем нужно создать свое меню и вернуть S_OK чтобы браузер "понял о чем его просят"). Устанавливаете его с помощью ICustomDoc::SetUIHandler.
Ниже приведен пример изменения контекстного меню, замена намного проще.
Пример:
Код:
// in hpp
#ifndef MainH
#define MainH
//---------------------------------------------------------------------------
#include <Classes.hpp>
#include <Controls.hpp>
#include <StdCtrls.hpp>
#include <Forms.hpp>
#include <Menus.hpp>
#include "mshtmhst.h"
#include "mshtmcid.h"
#include "atlbase.h"
#include "SHDocVw_OCX.h"
#include <OleCtrls.hpp>
//---------------------------------------------------------------------------
class TDocHandler : public IDocHostUIHandler
{
long refcount;
public:
TDocHandler():refcount(1){};
//IUnknown
virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID classid, void** intf) {
if (classid == IID_IUnknown)
*intf = (IUnknown*)this;
else if (classid == IID_IDocHostUIHandler)
*intf = (IDocHostUIHandler*)this;
else
return E_NOINTERFACE;
return S_OK;
}
virtual ULONG STDMETHODCALLTYPE AddRef() {
InterlockedIncrement(&refcount);
return refcount;
}
virtual ULONG STDMETHODCALLTYPE Release() {
InterlockedDecrement(&refcount);
if (refcount == 0)
delete this;
return refcount;
}
//IDocHostUIHandler
// Чтобы отключить контекстное меню надо вернуть S_OK
virtual HRESULT STDMETHODCALLTYPE ShowContextMenu(
/* [in] */ DWORD dwID,
/* [in] */ POINT __RPC_FAR *ppt,
/* [in] */ IUnknown __RPC_FAR *pcmdtReserved,
/* [in] */ IDispatch __RPC_FAR *pdispReserved) {
#define IDR_BROWSE_CONTEXT_MENU 24641
#define IDR_FORM_CONTEXT_MENU 24640
#define SHDVID_GETMIMECSETMENU 27
#define SHDVID_ADDMENUEXTENSIONS 53
HRESULT hr;
HINSTANCE hinstSHDOCLC;
HWND hwnd;
HMENU hMenu;
CComPtr<IOleCommandTarget> spCT;
CComPtr<IOleWindow> spWnd;
MENUITEMINFO mii = {0};
CComVariant var, var1, var2;
hr = pcmdtReserved->QueryInterface(IID_IOleCommandTarget, (void**)&spCT);
hr = pcmdtReserved->QueryInterface(IID_IOleWindow, (void**)&spWnd);
hr = spWnd->GetWindow(&hwnd);
hinstSHDOCLC = LoadLibrary(TEXT("SHDOCLC.DLL"));
hMenu = LoadMenu(hinstSHDOCLC,
MAKEINTRESOURCE(IDR_BROWSE_CONTEXT_MENU));
hMenu = GetSubMenu(hMenu, dwID);
// Iieo?aai iiaiai? aey ycueia eiae?iaee
hr = spCT->Exec(&CGID_ShellDocView, SHDVID_GETMIMECSETMENU, 0, NULL, &var);
mii.cbSize = sizeof(mii);
mii.fMask = MIIM_SUBMENU;
mii.hSubMenu = (HMENU) var.byref;
// Caiieiyai iai? Aea eiae?iaee
SetMenuItemInfo(hMenu, IDM_LANGUAGE, FALSE, &mii);
// Oaaeyai ioieo iai? Iieacaou a aeaa HTML
DeleteMenu(hMenu, IDM_VIEWSOURCE, MF_BYCOMMAND);
int iSelection = ::TrackPopupMenu(hMenu,
TPM_LEFTALIGN | TPM_RIGHTBUTTON | TPM_RETURNCMD, ppt->x, ppt->y, 0, hwnd, (RECT*)NULL);
// Ia?anueaai aua?aiio? eiiaiao ieio a?ioca?a
LRESULT lr = ::SendMessage(hwnd, WM_COMMAND, iSelection, NULL);
FreeLibrary(hinstSHDOCLC);
return S_OK;
// Return S_OK to tell MSHTML not to display its own menu
// Return S_FALSE displays default MSHTML menu
}
virtual HRESULT STDMETHODCALLTYPE GetHostInfo(
/* [out][in] */ DOCHOSTUIINFO __RPC_FAR *pInfo) {
if (pInfo == NULL)
return E_POINTER;
pInfo->cbSize = sizeof(DOCHOSTUIINFO);
pInfo->dwFlags &= ~DOCHOSTUIFLAG_DIALOG;
/*DOCHOSTUIFLAG_DIALOG
MSHTML does not enable selection of the text in the form
*/
return S_OK;
// return E_NOTIMPL;
}
virtual HRESULT STDMETHODCALLTYPE ShowUI(
/* [in] */ DWORD dwID,
/* [in] */ IOleInPlaceActiveObject __RPC_FAR *pActiveObject,
/* [in] */ IOleCommandTarget __RPC_FAR *pCommandTarget,
/* [in] */ IOleInPlaceFrame __RPC_FAR *pFrame,
/* [in] */ IOleInPlaceUIWindow __RPC_FAR *pDoc) {
return E_NOTIMPL;
}
virtual HRESULT STDMETHODCALLTYPE HideUI( void) {
return E_NOTIMPL;
}
virtual HRESULT STDMETHODCALLTYPE UpdateUI( void) {
return E_NOTIMPL;
}
virtual HRESULT STDMETHODCALLTYPE EnableModeless(
/* [in] */ BOOL fEnable) {
return E_NOTIMPL;
}
virtual HRESULT STDMETHODCALLTYPE OnDocWindowActivate(
/* [in] */ BOOL fActivate) {
return E_NOTIMPL;
}
virtual HRESULT STDMETHODCALLTYPE OnFrameWindowActivate(
/* [in] */ BOOL fActivate) {
return E_NOTIMPL;
}
virtual HRESULT STDMETHODCALLTYPE ResizeBorder(
/* [in] */ LPCRECT prcBorder,
/* [in] */ IOleInPlaceUIWindow __RPC_FAR *pUIWindow,
/* [in] */ BOOL fRameWindow) {
return E_NOTIMPL;
}
virtual HRESULT STDMETHODCALLTYPE TranslateAccelerator(
/* [in] */ LPMSG lpMsg,
/* [in] */ const GUID __RPC_FAR *pguidCmdGroup,
/* [in] */ DWORD nCmdID) {
return E_NOTIMPL;
}
virtual HRESULT STDMETHODCALLTYPE GetOptionKeyPath(
/* [out] */ LPOLESTR __RPC_FAR *pchKey,
/* [in] */ DWORD dw) {
return E_NOTIMPL;
}
virtual HRESULT STDMETHODCALLTYPE GetDropTarget(
/* [in] */ IDropTarget __RPC_FAR *pDropTarget,
/* [out] */ IDropTarget __RPC_FAR *__RPC_FAR *ppDropTarget) {
return E_NOTIMPL;
}
virtual HRESULT STDMETHODCALLTYPE GetExternal(
/* [out] */ IDispatch __RPC_FAR *__RPC_FAR *ppDispatch) {
return E_NOTIMPL;
}
virtual HRESULT STDMETHODCALLTYPE TranslateUrl(
/* [in] */ DWORD dwTranslate,
/* [in] */ OLECHAR __RPC_FAR *pchURLIn,
/* [out] */ OLECHAR __RPC_FAR *__RPC_FAR *ppchURLOut) {
return E_NOTIMPL;
}
virtual HRESULT STDMETHODCALLTYPE FilterDataObject(
/* [in] */ IDataObject __RPC_FAR *pDO,
/* [out] */ IDataObject __RPC_FAR *__RPC_FAR *ppDORet) {
return E_NOTIMPL;
}
};
//---------------------------------------------------------------------------
class TForm1 : public TForm
{
__published: // IDE-managed Components
TCppWebBrowser *CppWebBrowser1;
void __fastcall CppWebBrowser1NavigateComplete2(TObject *Sender,
LPDISPATCH pDisp, TVariant *URL);
void __fastcall CppWebBrowser1DocumentComplete(TObject *Sender,
LPDISPATCH pDisp, TVariant *URL);
private: // User declarations
TDocHandler* dochandler;
_di_IDispatch CurDispatch;
public: // User declarations
__fastcall TForm1(TComponent* Owner);
__fastcall ~TForm1();
public:
};
//---------------------------------------------------------------------------
extern PACKAGE TForm1 *Form1;
//---------------------------------------------------------------------------
#endif
// in cpp
#include <vcl.h>
#pragma hdrstop
#include "Main.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "SHDocVw_OCX"
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
dochandler = new TDocHandler();
CppWebBrowser1->GoHome();
}
//---------------------------------------------------------------------------
__fastcall TForm1::~TForm1() {
dochandler->Release();
}
//---------------------------------------------------------------------------
void __fastcall TForm1::CppWebBrowser1NavigateComplete2(TObject *Sender,
LPDISPATCH pDisp, TVariant *URL)
{
if (!CurDispatch)
CurDispatch = pDisp; // save for comparison
}
//---------------------------------------------------------------------------
void __fastcall TForm1::CppWebBrowser1DocumentComplete(TObject *Sender,
LPDISPATCH pDisp, TVariant *URL)
{
if (CurDispatch && pDisp == CurDispatch)
{
// the document is loaded, not just a frame
CurDispatch = NULL; //clear the global variable
// Set this class to be the IDocHostUIHandler
CComQIPtr<ICustomDoc, &IID_ICustomDoc> pCustomDoc(CppWebBrowser1->Document);
if (pCustomDoc)
pCustomDoc->SetUIHandler(dochandler);
}
}
#ifndef MainH
#define MainH
//---------------------------------------------------------------------------
#include <Classes.hpp>
#include <Controls.hpp>
#include <StdCtrls.hpp>
#include <Forms.hpp>
#include <Menus.hpp>
#include "mshtmhst.h"
#include "mshtmcid.h"
#include "atlbase.h"
#include "SHDocVw_OCX.h"
#include <OleCtrls.hpp>
//---------------------------------------------------------------------------
class TDocHandler : public IDocHostUIHandler
{
long refcount;
public:
TDocHandler():refcount(1){};
//IUnknown
virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID classid, void** intf) {
if (classid == IID_IUnknown)
*intf = (IUnknown*)this;
else if (classid == IID_IDocHostUIHandler)
*intf = (IDocHostUIHandler*)this;
else
return E_NOINTERFACE;
return S_OK;
}
virtual ULONG STDMETHODCALLTYPE AddRef() {
InterlockedIncrement(&refcount);
return refcount;
}
virtual ULONG STDMETHODCALLTYPE Release() {
InterlockedDecrement(&refcount);
if (refcount == 0)
delete this;
return refcount;
}
//IDocHostUIHandler
// Чтобы отключить контекстное меню надо вернуть S_OK
virtual HRESULT STDMETHODCALLTYPE ShowContextMenu(
/* [in] */ DWORD dwID,
/* [in] */ POINT __RPC_FAR *ppt,
/* [in] */ IUnknown __RPC_FAR *pcmdtReserved,
/* [in] */ IDispatch __RPC_FAR *pdispReserved) {
#define IDR_BROWSE_CONTEXT_MENU 24641
#define IDR_FORM_CONTEXT_MENU 24640
#define SHDVID_GETMIMECSETMENU 27
#define SHDVID_ADDMENUEXTENSIONS 53
HRESULT hr;
HINSTANCE hinstSHDOCLC;
HWND hwnd;
HMENU hMenu;
CComPtr<IOleCommandTarget> spCT;
CComPtr<IOleWindow> spWnd;
MENUITEMINFO mii = {0};
CComVariant var, var1, var2;
hr = pcmdtReserved->QueryInterface(IID_IOleCommandTarget, (void**)&spCT);
hr = pcmdtReserved->QueryInterface(IID_IOleWindow, (void**)&spWnd);
hr = spWnd->GetWindow(&hwnd);
hinstSHDOCLC = LoadLibrary(TEXT("SHDOCLC.DLL"));
hMenu = LoadMenu(hinstSHDOCLC,
MAKEINTRESOURCE(IDR_BROWSE_CONTEXT_MENU));
hMenu = GetSubMenu(hMenu, dwID);
// Iieo?aai iiaiai? aey ycueia eiae?iaee
hr = spCT->Exec(&CGID_ShellDocView, SHDVID_GETMIMECSETMENU, 0, NULL, &var);
mii.cbSize = sizeof(mii);
mii.fMask = MIIM_SUBMENU;
mii.hSubMenu = (HMENU) var.byref;
// Caiieiyai iai? Aea eiae?iaee
SetMenuItemInfo(hMenu, IDM_LANGUAGE, FALSE, &mii);
// Oaaeyai ioieo iai? Iieacaou a aeaa HTML
DeleteMenu(hMenu, IDM_VIEWSOURCE, MF_BYCOMMAND);
int iSelection = ::TrackPopupMenu(hMenu,
TPM_LEFTALIGN | TPM_RIGHTBUTTON | TPM_RETURNCMD, ppt->x, ppt->y, 0, hwnd, (RECT*)NULL);
// Ia?anueaai aua?aiio? eiiaiao ieio a?ioca?a
LRESULT lr = ::SendMessage(hwnd, WM_COMMAND, iSelection, NULL);
FreeLibrary(hinstSHDOCLC);
return S_OK;
// Return S_OK to tell MSHTML not to display its own menu
// Return S_FALSE displays default MSHTML menu
}
virtual HRESULT STDMETHODCALLTYPE GetHostInfo(
/* [out][in] */ DOCHOSTUIINFO __RPC_FAR *pInfo) {
if (pInfo == NULL)
return E_POINTER;
pInfo->cbSize = sizeof(DOCHOSTUIINFO);
pInfo->dwFlags &= ~DOCHOSTUIFLAG_DIALOG;
/*DOCHOSTUIFLAG_DIALOG
MSHTML does not enable selection of the text in the form
*/
return S_OK;
// return E_NOTIMPL;
}
virtual HRESULT STDMETHODCALLTYPE ShowUI(
/* [in] */ DWORD dwID,
/* [in] */ IOleInPlaceActiveObject __RPC_FAR *pActiveObject,
/* [in] */ IOleCommandTarget __RPC_FAR *pCommandTarget,
/* [in] */ IOleInPlaceFrame __RPC_FAR *pFrame,
/* [in] */ IOleInPlaceUIWindow __RPC_FAR *pDoc) {
return E_NOTIMPL;
}
virtual HRESULT STDMETHODCALLTYPE HideUI( void) {
return E_NOTIMPL;
}
virtual HRESULT STDMETHODCALLTYPE UpdateUI( void) {
return E_NOTIMPL;
}
virtual HRESULT STDMETHODCALLTYPE EnableModeless(
/* [in] */ BOOL fEnable) {
return E_NOTIMPL;
}
virtual HRESULT STDMETHODCALLTYPE OnDocWindowActivate(
/* [in] */ BOOL fActivate) {
return E_NOTIMPL;
}
virtual HRESULT STDMETHODCALLTYPE OnFrameWindowActivate(
/* [in] */ BOOL fActivate) {
return E_NOTIMPL;
}
virtual HRESULT STDMETHODCALLTYPE ResizeBorder(
/* [in] */ LPCRECT prcBorder,
/* [in] */ IOleInPlaceUIWindow __RPC_FAR *pUIWindow,
/* [in] */ BOOL fRameWindow) {
return E_NOTIMPL;
}
virtual HRESULT STDMETHODCALLTYPE TranslateAccelerator(
/* [in] */ LPMSG lpMsg,
/* [in] */ const GUID __RPC_FAR *pguidCmdGroup,
/* [in] */ DWORD nCmdID) {
return E_NOTIMPL;
}
virtual HRESULT STDMETHODCALLTYPE GetOptionKeyPath(
/* [out] */ LPOLESTR __RPC_FAR *pchKey,
/* [in] */ DWORD dw) {
return E_NOTIMPL;
}
virtual HRESULT STDMETHODCALLTYPE GetDropTarget(
/* [in] */ IDropTarget __RPC_FAR *pDropTarget,
/* [out] */ IDropTarget __RPC_FAR *__RPC_FAR *ppDropTarget) {
return E_NOTIMPL;
}
virtual HRESULT STDMETHODCALLTYPE GetExternal(
/* [out] */ IDispatch __RPC_FAR *__RPC_FAR *ppDispatch) {
return E_NOTIMPL;
}
virtual HRESULT STDMETHODCALLTYPE TranslateUrl(
/* [in] */ DWORD dwTranslate,
/* [in] */ OLECHAR __RPC_FAR *pchURLIn,
/* [out] */ OLECHAR __RPC_FAR *__RPC_FAR *ppchURLOut) {
return E_NOTIMPL;
}
virtual HRESULT STDMETHODCALLTYPE FilterDataObject(
/* [in] */ IDataObject __RPC_FAR *pDO,
/* [out] */ IDataObject __RPC_FAR *__RPC_FAR *ppDORet) {
return E_NOTIMPL;
}
};
//---------------------------------------------------------------------------
class TForm1 : public TForm
{
__published: // IDE-managed Components
TCppWebBrowser *CppWebBrowser1;
void __fastcall CppWebBrowser1NavigateComplete2(TObject *Sender,
LPDISPATCH pDisp, TVariant *URL);
void __fastcall CppWebBrowser1DocumentComplete(TObject *Sender,
LPDISPATCH pDisp, TVariant *URL);
private: // User declarations
TDocHandler* dochandler;
_di_IDispatch CurDispatch;
public: // User declarations
__fastcall TForm1(TComponent* Owner);
__fastcall ~TForm1();
public:
};
//---------------------------------------------------------------------------
extern PACKAGE TForm1 *Form1;
//---------------------------------------------------------------------------
#endif
// in cpp
#include <vcl.h>
#pragma hdrstop
#include "Main.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "SHDocVw_OCX"
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
dochandler = new TDocHandler();
CppWebBrowser1->GoHome();
}
//---------------------------------------------------------------------------
__fastcall TForm1::~TForm1() {
dochandler->Release();
}
//---------------------------------------------------------------------------
void __fastcall TForm1::CppWebBrowser1NavigateComplete2(TObject *Sender,
LPDISPATCH pDisp, TVariant *URL)
{
if (!CurDispatch)
CurDispatch = pDisp; // save for comparison
}
//---------------------------------------------------------------------------
void __fastcall TForm1::CppWebBrowser1DocumentComplete(TObject *Sender,
LPDISPATCH pDisp, TVariant *URL)
{
if (CurDispatch && pDisp == CurDispatch)
{
// the document is loaded, not just a frame
CurDispatch = NULL; //clear the global variable
// Set this class to be the IDocHostUIHandler
CComQIPtr<ICustomDoc, &IID_ICustomDoc> pCustomDoc(CppWebBrowser1->Document);
if (pCustomDoc)
pCustomDoc->SetUIHandler(dochandler);
}
}
Автор ответа: ***
Мне нужен динамически созданный CppWebBrowser на всю форму?
Пример:
Код:
void __fastcall TForm1::FormCreate(TObject *Sender)
{
TCppWebBrowser *CppWebBrowser = new TCppWebBrowser ( this );
CppWebBrowser->TOleControl::Parent = this;
CppWebBrowser->Align = alClient;
CppWebBrowser->Navigate(WideString("http://forum.codenet.ru/newreply.php?do=newreply&p=124529"));
}
{
TCppWebBrowser *CppWebBrowser = new TCppWebBrowser ( this );
CppWebBrowser->TOleControl::Parent = this;
CppWebBrowser->Align = alClient;
CppWebBrowser->Navigate(WideString("http://forum.codenet.ru/newreply.php?do=newreply&p=124529"));
}
Автор ответа: ***
Отловить MouseMove над CppWebBrowser?
Пример:
Код:
// in hpp
#ifndef MainH
#define MainH
//---------------------------------------------------------------------------
#include <Classes.hpp>
#include <Controls.hpp>
#include <StdCtrls.hpp>
#include <Forms.hpp>
#include "mshtml.h"
#include "mshtmdid.h"
#include "SHDocVw_OCX.h"
#include <OleCtrls.hpp>
#include <ExtCtrls.hpp>
//---------------------------------------------------------------------------
typedef void __fastcall (__closure *TOnMouseMove)();
//---------------------------------------------------------------------------
class THtmlEventSink : public IDispatch
{
protected:
TOnMouseMove FOnMouseMove;
public:
THtmlEventSink() { m_cRef = 0; }
~THtmlEventSink() { /*ShowMessage("~THtmlEventSink()");*/} // trace it work
HRESULT __stdcall QueryInterface(REFIID riid, void** ppvObject)
{
*ppvObject = NULL;
if (IsEqualGUID(riid, IID_IUnknown))
*ppvObject = reinterpret_cast<void**>(this);
if (IsEqualGUID(riid, IID_IDispatch))
*ppvObject = reinterpret_cast<void**>(this);
if (*ppvObject)
{
((IUnknown*)*ppvObject)->AddRef();
return S_OK;
}
else return E_NOINTERFACE;
}
DWORD __stdcall AddRef()
{
return InterlockedIncrement(&m_cRef);
}
DWORD __stdcall Release()
{
if (InterlockedDecrement(&m_cRef) == 0)
{
delete this;
return 0;
}
return m_cRef;
}
STDMETHOD(GetTypeInfoCount)(unsigned int FAR* pctinfo)
{ return E_NOTIMPL; }
STDMETHOD(GetTypeInfo)(unsigned int iTInfo, LCID lcid, ITypeInfo FAR* FAR* ppTInfo)
{ return E_NOTIMPL; }
STDMETHOD(GetIDsOfNames)(REFIID riid, OLECHAR FAR* FAR* rgszNames, unsigned int cNames, LCID lcid, DISPID FAR* rgDispId)
{ return S_OK; }
STDMETHOD(Invoke)(DISPID dispIdMember, REFIID riid, LCID lcid,
WORD wFlags, DISPPARAMS* pDispParams, VARIANT* pVarResult,
EXCEPINFO * pExcepInfo, UINT * puArgErr)
{
if (FOnMouseMove != NULL)
FOnMouseMove();
return S_OK;
}
public:
__property TOnMouseMove OnMouseMove = {read = FOnMouseMove, write = FOnMouseMove};
protected:
long m_cRef;
};
//---------------------------------------------------------------------------
class TForm1 : public TForm
{
__published: // IDE-managed Components
TCppWebBrowser *CppWebBrowser1;
TMemo *Memo1;
TPanel *Panel1;
TEdit *Edit1;
TButton *Button1;
void __fastcall Button1Click(TObject *Sender);
void __fastcall CppWebBrowser1DocumentComplete(TObject *Sender,
LPDISPATCH pDisp, TVariant *URL);
void __fastcall CppWebBrowser1NavigateComplete2(TObject *Sender,
LPDISPATCH pDisp, TVariant *URL);
private: // User declarations
void __fastcall OnMouseMove();
_di_IDispatch CurDispatch;
public: // User declarations
__fastcall TForm1(TComponent* Owner);
};
//---------------------------------------------------------------------------
extern PACKAGE TForm1 *Form1;
//---------------------------------------------------------------------------
#endif
//in cpp
#include <vcl.h>
#pragma hdrstop
#include "Main.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "SHDocVw_OCX"
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
CurDispatch = NULL;
CppWebBrowser1->Navigate(WideString("http://www.codenet.ru"));
}
//---------------------------------------------------------------------------
void __fastcall TForm1::OnMouseMove()
{
long cx;
long cy;
TComInterface<IHTMLDocument2> pDoc;
CppWebBrowser1->Document->QueryInterface(IID_IHTMLDocument2, (LPVOID*)&pDoc);
TComInterface<IHTMLWindow2> pWin;
TComInterface<IHTMLEventObj> pEvent;
pDoc->get_parentWindow( &pWin);
pWin->get_event( &pEvent);
if (pEvent)
{
pEvent->get_clientX( &cx);
pEvent->get_clientY( &cy);
}
String Str;
Str.printf("X = %d: Y = %d)", cx,cy);
Memo1->Lines->Add( Str);
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
CppWebBrowser1->Navigate(WideString(Edit1->Text));
}
//---------------------------------------------------------------------------
void __fastcall TForm1::CppWebBrowser1DocumentComplete(TObject *Sender,
LPDISPATCH pDisp, TVariant *URL)
{
if (pDisp == CurDispatch)
{
// the document is loaded, not just a frame
CurDispatch = NULL; //clear the global variable
IHTMLDocument2* pDoc;
CppWebBrowser1->Document->QueryInterface(IID_IHTMLDocument2, (LPVOID*)&pDoc);
THtmlEventSink* EventSink = new THtmlEventSink();
EventSink->OnMouseMove = OnMouseMove;
VARIANT vIn;
V_VT(&vIn) = VT_DISPATCH;
V_DISPATCH(&vIn) = EventSink;
// put onmousemove
if(SUCCEEDED(pDoc->put_onmousemove( vIn )))
;//ShowMessage("ConnectEvent: onmousemove");
pDoc->Release();
}
}
//---------------------------------------------------------------------------
void __fastcall TForm1::CppWebBrowser1NavigateComplete2(TObject *Sender,
LPDISPATCH pDisp, TVariant *URL)
{
if (!CurDispatch)
CurDispatch = pDisp; // save for comparison
}
#ifndef MainH
#define MainH
//---------------------------------------------------------------------------
#include <Classes.hpp>
#include <Controls.hpp>
#include <StdCtrls.hpp>
#include <Forms.hpp>
#include "mshtml.h"
#include "mshtmdid.h"
#include "SHDocVw_OCX.h"
#include <OleCtrls.hpp>
#include <ExtCtrls.hpp>
//---------------------------------------------------------------------------
typedef void __fastcall (__closure *TOnMouseMove)();
//---------------------------------------------------------------------------
class THtmlEventSink : public IDispatch
{
protected:
TOnMouseMove FOnMouseMove;
public:
THtmlEventSink() { m_cRef = 0; }
~THtmlEventSink() { /*ShowMessage("~THtmlEventSink()");*/} // trace it work
HRESULT __stdcall QueryInterface(REFIID riid, void** ppvObject)
{
*ppvObject = NULL;
if (IsEqualGUID(riid, IID_IUnknown))
*ppvObject = reinterpret_cast<void**>(this);
if (IsEqualGUID(riid, IID_IDispatch))
*ppvObject = reinterpret_cast<void**>(this);
if (*ppvObject)
{
((IUnknown*)*ppvObject)->AddRef();
return S_OK;
}
else return E_NOINTERFACE;
}
DWORD __stdcall AddRef()
{
return InterlockedIncrement(&m_cRef);
}
DWORD __stdcall Release()
{
if (InterlockedDecrement(&m_cRef) == 0)
{
delete this;
return 0;
}
return m_cRef;
}
STDMETHOD(GetTypeInfoCount)(unsigned int FAR* pctinfo)
{ return E_NOTIMPL; }
STDMETHOD(GetTypeInfo)(unsigned int iTInfo, LCID lcid, ITypeInfo FAR* FAR* ppTInfo)
{ return E_NOTIMPL; }
STDMETHOD(GetIDsOfNames)(REFIID riid, OLECHAR FAR* FAR* rgszNames, unsigned int cNames, LCID lcid, DISPID FAR* rgDispId)
{ return S_OK; }
STDMETHOD(Invoke)(DISPID dispIdMember, REFIID riid, LCID lcid,
WORD wFlags, DISPPARAMS* pDispParams, VARIANT* pVarResult,
EXCEPINFO * pExcepInfo, UINT * puArgErr)
{
if (FOnMouseMove != NULL)
FOnMouseMove();
return S_OK;
}
public:
__property TOnMouseMove OnMouseMove = {read = FOnMouseMove, write = FOnMouseMove};
protected:
long m_cRef;
};
//---------------------------------------------------------------------------
class TForm1 : public TForm
{
__published: // IDE-managed Components
TCppWebBrowser *CppWebBrowser1;
TMemo *Memo1;
TPanel *Panel1;
TEdit *Edit1;
TButton *Button1;
void __fastcall Button1Click(TObject *Sender);
void __fastcall CppWebBrowser1DocumentComplete(TObject *Sender,
LPDISPATCH pDisp, TVariant *URL);
void __fastcall CppWebBrowser1NavigateComplete2(TObject *Sender,
LPDISPATCH pDisp, TVariant *URL);
private: // User declarations
void __fastcall OnMouseMove();
_di_IDispatch CurDispatch;
public: // User declarations
__fastcall TForm1(TComponent* Owner);
};
//---------------------------------------------------------------------------
extern PACKAGE TForm1 *Form1;
//---------------------------------------------------------------------------
#endif
//in cpp
#include <vcl.h>
#pragma hdrstop
#include "Main.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "SHDocVw_OCX"
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
CurDispatch = NULL;
CppWebBrowser1->Navigate(WideString("http://www.codenet.ru"));
}
//---------------------------------------------------------------------------
void __fastcall TForm1::OnMouseMove()
{
long cx;
long cy;
TComInterface<IHTMLDocument2> pDoc;
CppWebBrowser1->Document->QueryInterface(IID_IHTMLDocument2, (LPVOID*)&pDoc);
TComInterface<IHTMLWindow2> pWin;
TComInterface<IHTMLEventObj> pEvent;
pDoc->get_parentWindow( &pWin);
pWin->get_event( &pEvent);
if (pEvent)
{
pEvent->get_clientX( &cx);
pEvent->get_clientY( &cy);
}
String Str;
Str.printf("X = %d: Y = %d)", cx,cy);
Memo1->Lines->Add( Str);
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
CppWebBrowser1->Navigate(WideString(Edit1->Text));
}
//---------------------------------------------------------------------------
void __fastcall TForm1::CppWebBrowser1DocumentComplete(TObject *Sender,
LPDISPATCH pDisp, TVariant *URL)
{
if (pDisp == CurDispatch)
{
// the document is loaded, not just a frame
CurDispatch = NULL; //clear the global variable
IHTMLDocument2* pDoc;
CppWebBrowser1->Document->QueryInterface(IID_IHTMLDocument2, (LPVOID*)&pDoc);
THtmlEventSink* EventSink = new THtmlEventSink();
EventSink->OnMouseMove = OnMouseMove;
VARIANT vIn;
V_VT(&vIn) = VT_DISPATCH;
V_DISPATCH(&vIn) = EventSink;
// put onmousemove
if(SUCCEEDED(pDoc->put_onmousemove( vIn )))
;//ShowMessage("ConnectEvent: onmousemove");
pDoc->Release();
}
}
//---------------------------------------------------------------------------
void __fastcall TForm1::CppWebBrowser1NavigateComplete2(TObject *Sender,
LPDISPATCH pDisp, TVariant *URL)
{
if (!CurDispatch)
CurDispatch = pDisp; // save for comparison
}
Автор ответа: ***