Текущий архив: 2007.05.20;
Скачать: CL | DM;
Вниз
Как извлечь выделеный текст из Opera и Internet Explorer-a? Найти похожие ветки
← →
MasteroK (2006-12-17 18:11) [0](хочу извлечь выделеный текст из оперы)
(Internet Explorer - доступа на даёт, хотя WebBrowser с таким же интерфейсом отзывается)
Хочется раздобыть интерфейс к окну оперы(API) OperaWindowClass и к класу перетаскивания выделенного текста CLIPBRDWNDCLASS, а так же доступ к интерфейсу IHTMLDocument2 класса Internet Explorer_Server в программе InternetExplorer (к WebBrowser-у в Delphi доступ есть). Сделал удобный словарик, хочется сделать ещё удобней - работаю в Delphi с использованием собственноручно написаных библиотек на Delphi и в VisualStudi-и на C++.
Вопросы, на которые хочется получить ответы:
1) Не знаю я интерфейса окон оперы. И заголовочных файлов ет а очень хочется.
2) Хочу заставить Internet Explorer отозваться на мои запросы, ebBrowser же отвечает.
3) Альтернатива: заставить Оперу или Internet Explorer копировать выделеный текст в
буфер обмена(Clipboard). SendMessage(HWND, WM_COPY,0,0) — аботает тока на Edit-ы.
Сканер(ловушка): операция копиравания не показавает икаких сообщений кроме нажатых клавиш и всяких User-ских сообщений.
4) Самый простой вопрос — создать обработчик события бновления буфера обмена.
5) Определить размер буфера обмена.(длину текста).
Далее привожу код библиотеки пытыющейся возвратить текст из Internet Explorer-a
и библиотека-ловушка сообщений всяких приложений.
← →
MasteroK (2006-12-17 18:12) [1]библиотека GetInterfaceFromHTML_DLL.dll(в VisualStudio 6.0)
// HTMLFROMHWND.cpp : Defines the entry point for the DLL application.
//
#include "stdafx.h"
#include <atlbase.h>
#include <oleacc.h>
BOOL CALLBACK EnumChildProc(HWND hwnd,LPARAM lParam)
//bool EnumChildProc(HWND hwnd,LPARAM lParam)
{
TCHAR buf[100];
int l=::GetClassName( hwnd, (LPTSTR)&buf, 100 );
// HDC DC=GetDC(0);
// TextOutA(DC,0,280,(LPTSTR)&buf,l);
// ReleaseDC(0,DC);
if ( _tcscmp( buf, _T("Internet Explorer_Server") ) == 0 ) {if (!lParam) *(HWND*)lParam = hwnd; return FALSE;}
else if ( _tcscmp( buf, _T("OperaWindowClass") ) == 0 ) {if (!lParam) *(HWND*)lParam = hwnd; return FALSE;}
else return TRUE;
};
//You can store the interface pointer in a member variable
//for easier access
class CComPtrIHTMLDocument2
{
public:
typedef IHTMLDocument2 _PtrClass;
CComPtrIHTMLDocument2()
{
p=NULL;
}
CComPtrIHTMLDocument2(IHTMLDocument2* lp)
{
if ((p = lp) != NULL)
p->AddRef();
}
CComPtrIHTMLDocument2(const CComPtr<IHTMLDocument2>& lp)
{
if ((p = lp.p) != NULL)
p->AddRef();
}
~CComPtrIHTMLDocument2()
{
// if (p)
// p->Release();
}
void Release()
{
IUnknown* pTemp = p;
if (pTemp)
{
p = NULL;
pTemp->Release();
}
}
operator IHTMLDocument2*() const
{
return (IHTMLDocument2*)p;
}
IHTMLDocument2& operator*() const
{
ATLASSERT(p!=NULL);
return *p;
}
//The assert on operator& usually indicates a bug. If this is really
//what is needed, however, take the address of the p member explicitly.
IHTMLDocument2** operator&()
{
ATLASSERT(p==NULL);
return &p;
}
_NoAddRefReleaseOnCComPtr<IHTMLDocument2>* operator->() const
{
ATLASSERT(p!=NULL);
return (_NoAddRefReleaseOnCComPtr<IHTMLDocument2>*)p;
}
IHTMLDocument2* operator=(IHTMLDocument2* lp)
{
return (IHTMLDocument2*)AtlComPtrAssign((IUnknown**)&p, lp);
}
IHTMLDocument2* operator=(const CComPtr<IHTMLDocument2>& lp)
{
return (IHTMLDocument2*)AtlComPtrAssign((IUnknown**)&p, lp.p);
}
bool operator!() const
{
return (p == NULL);
}
bool operator<(IHTMLDocument2* pT) const
{
return p < pT;
}
bool operator==(IHTMLDocument2* pT) const
{
return p == pT;
}
// Compare two objects for equivalence
bool IsEqualObject(IUnknown* pOther)
{
if (p == NULL && pOther == NULL)
return true; // They are both NULL objects
if (p == NULL || pOther == NULL)
return false; // One is NULL the other is not
CComPtr<IUnknown> punk1;
CComPtr<IUnknown> punk2;
p->QueryInterface(IID_IUnknown, (void**)&punk1);
pOther->QueryInterface(IID_IUnknown, (void**)&punk2);
return punk1 == punk2;
}
void Attach(IHTMLDocument2* p2)
{
if (p)
p->Release();
p = p2;
}
IHTMLDocument2* Detach()
{
IHTMLDocument2* pt = p;
p = NULL;
return pt;
}
HRESULT CopyTo(IHTMLDocument2** ppT)
{
ATLASSERT(ppT != NULL);
if (ppT == NULL)
return E_POINTER;
*ppT = p;
if (p)
p->AddRef();
return S_OK;
}
HRESULT SetSite(IUnknown* punkParent)
{
return AtlSetChildSite(p, punkParent);
}
HRESULT Advise(IUnknown* pUnk, const IID& iid, LPDWORD pdw)
{
return AtlAdvise(p, pUnk, iid, pdw);
}
HRESULT CoCreateInstance(REFCLSID rclsid, LPUNKNOWN pUnkOuter = NULL, DWORD dwClsContext = CLSCTX_ALL)
{
ATLASSERT(p == NULL);
return ::CoCreateInstance(rclsid, pUnkOuter, dwClsContext, __uuidof(IHTMLDocument2), (void**)&p);
}
HRESULT CoCreateInstance(LPCOLESTR szProgID, LPUNKNOWN pUnkOuter = NULL, DWORD dwClsContext = CLSCTX_ALL)
{
CLSID clsid;
HRESULT hr = CLSIDFromProgID(szProgID, &clsid);
ATLASSERT(p == NULL);
if (SUCCEEDED(hr))
hr = ::CoCreateInstance(clsid, pUnkOuter, dwClsContext, __uuidof(IHTMLDocument2), (void**)&p);
return hr;
}
template <class Q>
HRESULT QueryInterface(Q** pp) const
{
ATLASSERT(pp != NULL && *pp == NULL);
return p->QueryInterface(__uuidof(Q), (void**)pp);
}
IHTMLDocument2* p;
};
typedef IHTMLDocument2* PIHTMLDocument2;
//__declspec( dllexport ) __stdcall
__declspec(dllexport) PIHTMLDocument2 __stdcall GetInterface(HWND hWnd, char **cs, BSTR *ws, int maxlen)
{
if (*ws) SysFreeString(*ws);
if (*cs) free(*cs);
PIHTMLDocument2 result=NULL;
CoInitialize( NULL );
// Explicitly load MSAA so we know if it"s installed
HINSTANCE hInst = ::LoadLibrary( _T("OLEACC.DLL") );
if ( hInst != NULL )
{
if ( hWnd != NULL )
{
/*HWND hWndChild=hWnd;
// Get 1st document window
//::EnumChildWindows( hWnd, EnumChildProc, (LPARAM)&hWndChild );
bool r = EnumChildProc(hWndChild,0);
if ( r )*/
HWND hWndChild=NULL;
// Get 1st document window
::EnumChildWindows( hWnd, EnumChildProc, (LPARAM)&hWndChild );
if ( !hWndChild ) {hWndChild=hWnd; EnumChildProc(hWndChild,(LPARAM)&hWndChild);}
if ( hWndChild )
{
CComPtrIHTMLDocument2 spDoc;
//spDoc.p=NULL;
LRESULT lRes;
UINT nMsg = ::RegisterWindowMessage( _T("WM_HTML_GETOBJECT") );
::SendMessageTimeout( hWndChild, nMsg, 0L, 0L, SMTO_ABORTIFHUNG, 1000, (DWORD*)&lRes );
LPFNOBJECTFROMLRESULT pfObjectFromLresult = (LPFNOBJECTFROMLRESULT)::GetProcAddress( hInst, _T("ObjectFromLresult") );
if ( pfObjectFromLresult != NULL )
{
HRESULT hr;
hr = (*pfObjectFromLresult)( lRes, IID_IHTMLDocument2, 0, (void**)&spDoc );
if ( SUCCEEDED(hr) )
{
Beep(200,100);
CComPtr<IDispatch> spDisp;
CComQIPtr<IHTMLWindow2> spWin;
//spDoc->get_Script( &spDisp );
//spWin = spDisp;
//spWin->get_document( &spDoc.p );
result=spDoc.p;
{
CComPtr<IDispatch> spDisp;
CComQIPtr<IHTMLSelectionObject> SelObl;
CComQIPtr<IHTMLTxtRange> range;
CComBSTR str;
// spDoc->get_title(&str);
spDoc->get_selection(&SelObl);
// HDC DC=GetDC(0);
// char *s; s=(char*)malloc(100);
// sprintf(s,"%i\0",(int)(void*)(SelObl.p));
// TextOutA(DC,0,300,s,strlen(s));
// TextOutW(DC,0,320,str.m_str,str.Length());
if ((void*)(SelObl.p)) {
SelObl->createRange(&spDisp.p);
range = spDisp;
range->get_text((BSTR*)&str);
// TextOutW(DC,0,320,str.m_str,str.Length());
}
(*ws)=str.m_str; str.m_str=NULL;
// ReleaseDC(0,DC);
};
//spDoc->put_bgColor( CComVariant("red") );
//Beep(200,100);
// Change background color to red
}
}
} // else document not ready
} // else Internet Explorer is not running
::FreeLibrary( hInst );
} // else Active Accessibility is not installed
CoUninitialize();
return result;
}
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
return TRUE;
}
← →
MasteroK (2006-12-17 18:13) [2]Hook.dll
library Hook;
uses
SysUtils, Classes, Windows, Messages;
const
{пользовательские сообщения}
wm_GetMSG_Event = wm_User + 133;
wm_GetMSG_Param = wm_User + 134;
wm_GetMSG_Result = wm_User + 135;
var
Wnd: Hwnd = 0;
Msg: Hwnd = 0;
H: HWND = 0;
{handle для ловушки}
HookHandle: hHook = 0;
function Msg_Hook(code: Integer; wparam: WPARAM; lparam: LPARAM): LRESULT stdcall; export;
var
lp,wp: LongInt;
begin
Result := CallNextHookEx(HookHandle, Code, wParam, lParam);
Msg:=TMsg(Pointer(lParam)^).message;
if (Msg=WM_LBUTTONUP) or (Msg=WM_KEYUP) then begin
H := FindWindow("TForm1", "XXX");
wp := TMsg(Pointer(lParam)^).wParam;
lp := TMsg(Pointer(lParam)^).lParam;
SendMessage(H, wm_GetMSG_Result, Result, 0);
SendMessage(H, wm_GetMSG_Param, wp, lp);
Wnd := TMsg(Pointer(lParam)^).hwnd;
SendMessage(H, wm_GetMSG_Event, integer(wnd), integer(msg));
end;
end;
procedure LocalExitProc; far;
begin
UnhookWindowsHookEx(HookHandle);
HookHandle := 0;
end;
procedure RunStop_Hook(State: Boolean; ThisHandle: HWND) stdcall; export;
begin
if State=true then
begin
H:=ThisHandle;
H := FindWindow("TForm1", "XXX");
HookHandle := SetWindowsHookEx(WH_GETMESSAGE, @Msg_Hook, hInstance, 0);
end else begin
UnhookWindowsHookEx(HookHandle);
HookHandle := 0;
end;
end;
exports RunStop_Hook;
begin
end.
Форма
unit ViewMSG;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, Grids, Mshtml;
const
wm_GetMSG_Event = wm_User + 133;
wm_GetMSG_Param = wm_User + 134;
wm_GetMSG_Result = wm_User + 135;
EM_GETSELTEXT = WM_USER + 62;
EM_GETTEXTEX = WM_USER + 94;
SB_GETTEXTA = (WM_USER+2);
SB_GETTEXTW = (WM_USER+13);
type
TForm1 = class(TForm)
procedure OnWinMSG(var Message: TMessage); message wm_GetMSG_Event;
procedure OnWinMSGParam(var Message: TMessage); message wm_GetMSG_Param;
procedure OnWinMSGResult(var Message: TMessage); message wm_GetMSG_Result;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
PIHTMLDocument2 = ^IHTMLDocument2;
var
Form1: TForm1;
DC: HDC;
WPrm,LPrm: Longint;
WPrmLo,LPrmLo,WPrmHi,LPrmHi: word;
LResult: LongInt;
HTMLDocument: PIHTMLDocument2;
ws: widestreng;
cs: PChar;
procedure RunStop_Hook(State: boolean; ThisHWND: HWND) stdcall; external "Hook" name "RunStop_Hook";
function GetInterfaceFromHWND(wnd: HWND; cs: PPChar; ws: PPWideChar; maxlen: integer): PIHTMLDocument2 stdcall; external "HTMLFROMHWND.dll" name "?GetInterface@@YGPAUIHTMLDocument2@@PAUHWND__@@PAPADPAPAGH@Z";//это имя нарыл в откомпилированой библиотеке рядом с именем этой библиотеки
implementation
{$R *.DFM}
procedure TForm1.OnWinMSGResult(var Message: TMessage);
begin
LResult:=message.WParam;
end;
procedure TForm2.OnWinMSGParam(var Message: TMessage);
begin
WPrm:=message.WParam;
LPrm:=message.LParam;
// WPrmLo:=message.WParamLo;
// WPrmHi:=message.WParamHi;
// LPrmLo:=message.LParamLo;
// LPrmHi:=message.LParamHi;
end;
procedure TForm1.OnWinMSG(var Message: TMessage);
var
msg: Cardinal;
wnd: HWND;
begin
if AllowViewMSG>=2 then begin
msg:=message.LParam;
wnd:=message.WParam;
case msg of
WM_LBUTTONUP: begin
HTMLDocument:=GetInterfaceFromHWND(wnd,cs,ws,0);
DC:=GetDC(0);
if (ws^<>nil) then TextOutW(DC,0,320,ws^,length(ws^));
ReleaseDC(0,DC);
end;
end;
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
new(ws); new(cs); ws^:=nil; cs^:=nil;
RunStop_Hook(true,Handle);
end;
procedure TForm2.FormDestroy(Sender: TObject);
begin
Dispose(ws); Dispose(cs);
RunStop_Hook(false,Handle);
Dec(AllowViewMSG);
end;
end.
← →
Rouse_ © (2006-12-18 10:21) [3]Зачем так сложно?
Вот тебе для IEunit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, MSHTML, OleCtrls, SHDocVw;
type
TObjectFromLResult = function(LRESULT: lResult; const IID: TGUID;
WPARAM: wParam; out pObject): HRESULT; stdcall;
TForm1 = class(TForm)
Edit1: TEdit;
Button1: TButton;
Memo1: TMemo;
WebBrowser1: TWebBrowser;
procedure Button1Click(Sender: TObject);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
function GetSelTextFromHWND_IE(WHandle: HWND; var Text: string): HRESULT;
var
hInst, Wnd: HWND;
lRes: Cardinal;
MSG: Integer;
ObjectFromLresult: TObjectFromLresult;
Doc: IHTMLDocument2;
begin
hInst := LoadLibrary("Oleacc.dll");
@ObjectFromLresult := GetProcAddress(hInst, "ObjectFromLresult");
if @ObjectFromLresult <> nil then begin
try
Wnd := FindWindowEX(WHandle, 0, "Shell DocObject View", nil);
Wnd := FindWindowEX(Wnd, 0, "Internet Explorer_Server", nil);
MSG := RegisterWindowMessage("WM_HTML_GETOBJECT");
SendMessageTimeOut(Wnd, MSG, 0, 0, SMTO_ABORTIFHUNG, 1000, lRes);
Result := ObjectFromLresult(lRes, IHTMLDocument2, 0, Doc);
if assigned(Doc) then
Text:= (Doc.selection.createRange as IHTMLTxtRange).Text;
finally
FreeLibrary(hInst);
end;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
Wnd: HWND;
Text: string;
begin
Wnd := FindWindow("IEFrame", nil);
if Wnd = 0 then
begin
ShowMessage("No Running instance of Internet Explorer");
Exit;
end;
if GetSelTextFromHWND_IE(Wnd, Text)=S_OK then
Memo1.Text:= Text;
end;
end.
Страницы: 1 вся ветка
Текущий архив: 2007.05.20;
Скачать: CL | DM;
Память: 0.5 MB
Время: 0.106 c