[RESUELTO] Asignar o configurar la Configuración LAN de Internet Explorer desde Delphi
#1
Escrito 09 octubre 2009 - 12:51
Saludos.
#2
Escrito 09 octubre 2009 - 01:49
Coloca un memo en un formulario y un botón y usa este código amigo
Function ObtenHtml(hReq: HINTERNET; Var PStlHtmlResult: TStringList): Boolean; Var LMstDestino: TMemoryStream; //Bufer dobnde se almacenarà el conetnido devuelto por el script de actualizaciòn LBuff: PByte; //Define la posiciòn que està copiando LCopiado: DWORD; //Almacena el tamaño de bloque por copiar. Begin Result := False; Try //FrmCarga.ArchivosLog('Obteniendo el còdigo html del recurso'); LMstDestino := TMemoryStream.Create; LBuff := AllocMem(GBUFF_SIZE); Try LCopiado := 1; While LCopiado > 0 do Begin InternetReadFile(hReq, LBuff, GBUFF_SIZE, LCopiado); If LCopiado > 0 then LMstDestino.WriteBuffer(LBuff^, LCopiado); End; // almacenar el caracter #0 terminador LBuff^ := 0; LMstDestino.WriteBuffer(LBuff, 1); Result := true; Finally FreeMem(LBuff, GBUFF_SIZE); PStlHtmlResult.SetText(PChar(LMstDestino.Memory)); LMstDestino.Free; End; Except On Err: Exception do ShowMessage('Error al establecer la comunicaciòn con el servidor Web. Error: ' + Err.Message); End; End; //Ejecuta el script php de actualizaciòn de tablas en el sitio de la tienda virtual Procedure EjecutaActualizacionSitioWeb; Var LSstrusername: String; //Define el usuario con que se validarà la conexiòn al proxy LSstruserpass: String; //Define el usuario con que se validarà la conexiòn al proxy LhInetInst: HINTERNET; //Almacena la instancia creada de la api WinInet LhInetConn: HINTERNET; //Almancena el handle de la conexiòn LhInetReq: HINTERNET; //Almacena el handle de las peticiones LDWData: DWORD; //variable que obtiene la repsuesta del servidor LCrdTam: Cardinal; //Almacena el tamaño en bytes que utiliza la variable LdwData LCrdPdwRes: Cardinal; //Define los indices de la cabecera devuelta por el servidor web LStlHtmlResult: TStringList; //Almacena la respuesta devuelta por el script de actualizaciòn LSDirProxy : String; //Alamacena la direccion del proxy LSDirLocal :String ; //Almacena las direcciones locales LSUserSite : String ; //Almacena usuario del sitio LSPasSite : String; //Almacena pasword del sitio Procedure Terminar; Begin Try if LhInetConn <> nil then InternetCloseHandle(LhInetConn); if LhInetReq <> nil then InternetCloseHandle(LhInetReq); if LhInetInst <> nil then InternetCloseHandle(LhInetInst); Screen.cursor := crDefault; Except On Err: Exception do ShowMessage('Error al liberar los recursos WinInet. Error: ' + Err.Message); End; End; Begin Try LStlHtmlResult := TStringList.Create; //Asigno la configuraciòn del proxy LSstrusername := 'edgram'; LSstruserpass := '77887788'; LSDirProxy := '192.168.1.12'; LSDirLocal := '192.168.1.12'; LhInetConn := nil; LhInetReq := nil; LhInetInst := InternetOpen('Descarga - Delphi',INTERNET_OPEN_TYPE_PROXY, Pchar(LSDirProxy),Pchar(LSDirLocal), INTERNET_FLAG_KEEP_CONNECTION); if LhInetInst = nil then Begin ShowMessage('Error al generar una instancia LhInetInst'); Terminar; End Else Begin //Establesco el tipo de conexion que se harà (http en este caso) LhInetConn := InternetConnect(LhInetInst,'[url=http://www.delphiaccess.com]www.delphiaccess.com[/url]',INTERNET_DEFAULT_HTTP_PORT, nil, nil,INTERNET_SERVICE_HTTP, INTERNET_FLAG_KEEP_CONNECTION, 0); if LhInetConn = nil then Begin ShowMessage('Error al crear la instancia LhInetConn'); Terminar End Else Begin //Realizò la conexiòn al recurzo definido por host LhInetReq := HttpOpenRequest(LhInetConn, 'GET','forum/index.php?board=29.0', 'HTTP/1.1',nil,nil, INTERNET_FLAG_KEEP_CONNECTION, 0); if LhInetReq = nil then Begin ShowMessage('Error al crear la instancia LhInetReq'); Terminar End Else Begin HttpSendRequest(LhInetReq, nil, 0, nil, 0); LCrdTam := sizeof(LDWData); LCrdPdwRes := 0; HttpQueryInfo(LhInetReq, HTTP_QUERY_STATUS_CODE or HTTP_QUERY_FLAG_NUMBER, @LDWData, LCrdTam, LCrdPdwRes); Case LDWData Of HTTP_STATUS_PROXY_AUTH_REQ: Begin ShowMessage('Autorización de proxy requerida, se reintenta la conexion'); InternetSetOption(LhInetReq,INTERNET_OPTION_PROXY_USERNAME,Pchar(LSstrusername), Length(LSstrusername) + 1); InternetSetOption(LhInetReq,INTERNET_OPTION_PROXY_PASSWORD,Pchar(LSstruserpass), Length(LSstruserpass) + 1); HttpSendRequest(LhInetReq, nil, 0, nil, 0); HttpQueryInfo(LhInetReq, HTTP_QUERY_STATUS_CODE or HTTP_QUERY_FLAG_NUMBER, @LDWData, LCrdTam, LCrdPdwRes); If LDWData = HTTP_STATUS_PROXY_AUTH_REQ Then Showmessage('La autorización del servidor proxy falló') Else If LDWData = HTTP_STATUS_OK Then begin ObtenHtml(LhInetReq,LStlHtmlResult); Form1.Memo1.Lines.Text := LStlHtmlResult.Text; End Else ShowMessage('Codigo devuelto: ' + InttoStr(LDWData)) End; //termina caso HTTP_STATUS_PROXY_AUTH_REQ HTTP_STATUS_OK: Begin ObtenHtml(LhInetReq,LStlHtmlResult); Form1.Memo1.Lines.Text := LStlHtmlResult.Text; End; Else ShowMessage('Codigo devuelto: ' + InttoStr(LDWData)); End;//Termina case End; End; End; Except On Err: Exception do ShowMessage('Error al establecer la comunicaciòn con el servidor Web. Error: ' + Err.Message); End; Terminar; end; procedure TForm1.Button1Click(Sender: TObject); begin EjecutaActualizacionSitioWeb; end;
#3
Escrito 09 octubre 2009 - 01:54
/////////////////////////////////////////////////////////////////////////////// // ProxyName = "proxy.mi.empresa-data.com:8080" // ProxyOverride = "local" BOOL SetConnectionOptions(char *ProxyName, char* ProxyOverride, bool Use) { INTERNET_PER_CONN_OPTION_LIST list; BOOL Result; DWORD dwBufSize = sizeof(list); // Rellenammos lo básico de la estructura list. list.dwSize = sizeof(list); // NULL == LAN, en otro caso es el nombre de la conexión. list.pszConnection = NULL; // Vamos a trabajar con tres opciones. list.dwOptionCount = 3; list.pOptions = new INTERNET_PER_CONN_OPTION[3]; // Nos aseguramos que tenemos un puntero válido. if( list.pOptions == NULL){ return FALSE; } // flags. list.pOptions[0].dwOption = INTERNET_PER_CONN_FLAGS; if(Use) list.pOptions[0].Value.dwValue = PROXY_TYPE_DIRECT | PROXY_TYPE_PROXY; else list.pOptions[0].Value.dwValue = 0; // proxy name. list.pOptions[1].dwOption = INTERNET_PER_CONN_PROXY_SERVER; list.pOptions[1].Value.pszValue = ProxyName; // proxy override. list.pOptions[2].dwOption = INTERNET_PER_CONN_PROXY_BYPASS; list.pOptions[2].Value.pszValue = ProxyOverride; // options on the connection. Result = InternetSetOption(NULL, INTERNET_OPTION_PER_CONNECTION_OPTION, &list, dwBufSize); // Liberamos memoria. delete [] list.pOptions; // Obligamos a refrescar y notificamos el cambio al sistema... InternetSetOption(0, INTERNET_OPTION_REFRESH, 0, 0); InternetSetOption(0, INTERNET_OPTION_SETTINGS_CHANGED, 0, 0); return Result; }
Saludos.
#4
Escrito 09 octubre 2009 - 02:20
Poliburro muchas gracias por el code, pero no es lo que busco, el problema radica en que muchas veces IE no tiene la opcion Tools->Connections la cual dificulta la configuración LAN manual. Pero de todos modos se navega .
Saludos
#5
Escrito 09 octubre 2009 - 02:46
#6
Escrito 09 octubre 2009 - 03:28
type INTERNET_PER_CONN_OPTION = record dwOption: DWORD; Value: DWORD; end; LPINTERNET_PER_CONN_OPTION = ^INTERNET_PER_CONN_OPTION; type INTERNET_PER_CONN_OPTION_LIST = record dwSize: DWORD; pszConnection: LPTSTR; dwOptionCount: DWORD; dwOptionError: DWORD; pOptions: LPINTERNET_PER_CONN_OPTION; end; LPINTERNET_PER_CONN_OPTION_LIST = ^INTERNET_PER_CONN_OPTION_LIST;
Saludos.
#7
Escrito 09 octubre 2009 - 03:48
function SetConnectionOptions(ProxyName: pchar; ProxyOverride: pchar; Use: boolean): Boolean; var List: INTERNET_PER_CONN_OPTION_LIST; dwBufSize: DWORD; begin dwBufSize := Sizeof(List); // Rellenammos lo básico de la estructura list. List.dwSize := sizeof(list); // NULL == LAN, en otro caso es el nombre de la conexión. list.pszConnection := 'NULL'; // Vamos a trabajar con tres opciones. list.dwOptionCount := 3; list.pOptions := INTERNET_PER_CONN_OPTION[3]; //[Error] Unit1.pas(60): '(' expected but '[' found // Nos aseguramos que tenemos un puntero válido. if list.pOptions = NULL then //[Error] Unit1.pas(63): Incompatible types Result := FALSE; // flags. list.pOptions.dwOption := INTERNET_PER_CONN_FLAGS; //[Error] Unit1.pas(67): Undeclared identifier: 'INTERNET_PER_CONN_FLAGS' if Use then list.pOptions.Value := PROXY_TYPE_DIRECT + PROXY_TYPE_PROXY //[Error] Unit1.pas(69): Undeclared identifier: 'PROXY_TYPE_DIRECT' y el otro también else list.pOptions.Value := 0; // proxy name. list.pOptions[1].dwOption := INTERNET_PER_CONN_PROXY_SERVER; //[Error] Unit1.pas(74): Array type required y [Error] Unit1.pas(74): Undeclared identifier: 'INTERNET_PER_CONN_PROXY_SERVER' list.pOptions[1].Value.pszValue := ProxyName; //[Error] Unit1.pas(75): Array type required // proxy override. list.pOptions[2].dwOption := INTERNET_PER_CONN_PROXY_BYPASS; //[Error] Unit1.pas(78): Undeclared identifier: 'INTERNET_PER_CONN_PROXY_BYPASS' list.pOptions[2].Value.pszValue := ProxyOverride; //Array Type Required // options on the connection. Result := InternetSetOption(NULL, INTERNET_OPTION_PER_CONNECTION_OPTION, ^list, dwBufSize); //[Error] Unit1.pas(82): Incompatible types: 'Variant' and 'Pointer' y [Error] Unit1.pas(82): Incompatible types: 'Char' and 'Pointer' //Liberamos de memoria List.free; // Obligamos a refrescar y notificamos el cambio al sistema... InternetSetOption(0, INTERNET_OPTION_REFRESH, 0, 0); InternetSetOption(0, INTERNET_OPTION_SETTINGS_CHANGED, 0, 0); Result := True; end;
Ahí están todos los errores de éste simple mortal
#8
Escrito 09 octubre 2009 - 03:55
type INTERNET_PER_CONN_OPTION = record dwOption: DWORD; case integer of 0:(dwValue: DWORD;); 1:(pszValue: LPTSTR;); 2:(ftValue: FILETIME;); end; LPINTERNET_PER_CONN_OPTION = ^INTERNET_PER_CONN_OPTION; type INTERNET_PER_CONN_OPTION_LIST = record dwSize: DWORD; pszConnection: LPTSTR; dwOptionCount: DWORD; dwOptionError: DWORD; pOptions: LPINTERNET_PER_CONN_OPTION; end; LPINTERNET_PER_CONN_OPTION_LIST = ^INTERNET_PER_CONN_OPTION_LIST; .... /////////////////////////////////////////////////////////////////////////////// // ProxyName = "proxy.mi.empresa-data.com:8080" // ProxyOverride = "local" function SetConnectionOptions(ProxyName: String; ProxyOverride: String; Use:bool): bool; var list: INTERNET_PER_CONN_OPTION_LIST; dwBufSize: DWORD; Options: array[0..2] of INTERNET_PER_CONN_OPTION; begin dwBufSize:= sizeof(list); // Rellenammos lo básico de la estructura list. list.dwSize:= sizeof(list); // NULL == LAN, en otro caso es el nombre de la conexión. list.pszConnection:= nil; // Vamos a trabajar con tres opciones. list.dwOptionCount:= 3; list.pOptions:= @(Options[0]); // flags. Options[0].dwOption:= 1; //INTERNET_PER_CONN_FLAGS; if(Use) then Options[0].dwValue:= 1 or 2 //PROXY_TYPE_DIRECT or PROXY_TYPE_PROXY; else Options[0].dwValue:= 0; // proxy name. Options[1].dwOption:= 2; //INTERNET_PER_CONN_PROXY_SERVER; Options[1].pszValue:= PCHAR(ProxyName); // proxy override. Options[2].dwOption:= 3; //INTERNET_PER_CONN_PROXY_BYPASS; Options[2].pszValue:= PCHAR(ProxyOverride); list.pOptions:= @(Options[0]); // options on the connection. Result:= InternetSetOption(nil, 75 {INTERNET_OPTION_PER_CONNECTION_OPTION}, @list, dwBufSize); // Obligamos a refrescar y notificamos el cambio al sistema... InternetSetOption(0, INTERNET_OPTION_REFRESH, 0, 0); InternetSetOption(0, INTERNET_OPTION_SETTINGS_CHANGED, 0, 0); end;
Usa esto como ejemplo y mira despues la configuración en el IExplorer, a mi me funciona.
SetConnectionOptions('proxy.mi.empresa-data.com:8080', '', true);
Saludos.
#9
Escrito 09 octubre 2009 - 04:02
function SetConnectionOptions(ProxyName: String; ProxyOverride: String; Use:bool): bool; var list: INTERNET_PER_CONN_OPTION_LIST; dwBufSize: DWORD; Options: array[0..2] of INTERNET_PER_CONN_OPTION; begin dwBufSize:= sizeof(list); // Rellenammos lo básico de la estructura list. list.dwSize:= sizeof(list); // NULL == LAN, en otro caso es el nombre de la conexión. list.pszConnection:= nil; // Vamos a trabajar con tres opciones. list.dwOptionCount:= 3; list.pOptions:= @(Options[0]); // flags. Options[0].dwOption:= 1; //INTERNET_PER_CONN_FLAGS; if(Use) then Options[0].Value:= 1 or 2 //PROXY_TYPE_DIRECT or PROXY_TYPE_PROXY; else Options[0].Value:= 0; // proxy name. Options[1].dwOption:= 2; //INTERNET_PER_CONN_PROXY_SERVER; Options[1].Value:= PCHAR(ProxyName); //[Error] Unit1.pas(73): Incompatible types: 'Cardinal' and 'PAnsiChar' // proxy override. Options[2].dwOption:= 3; //INTERNET_PER_CONN_PROXY_BYPASS; Options[2].Value:= PCHAR(ProxyOverride); //[Error] Unit1.pas(77): Incompatible types: 'Cardinal' and 'PAnsiChar' list.pOptions:= @(Options[0]); // options on the connection. Result:= InternetSetOption(nil, 75 {INTERNET_OPTION_PER_CONNECTION_OPTION}, @list, dwBufSize); // Obligamos a refrescar y notificamos el cambio al sistema... InternetSetOption(0, INTERNET_OPTION_REFRESH, 0, 0); InternetSetOption(0, INTERNET_OPTION_SETTINGS_CHANGED, 0, 0); end;
Salvo esos dos errores que señalo
#10
Escrito 09 octubre 2009 - 04:07
uses Registry; procedure EnableProxy(Server: String); begin with TRegistry.Create do try RootKey:= HKEY_CURRENT_USER; if OpenKey('Software\Microsoft\Windows\CurrentVersion\Internet Settings',FALSE) then begin WriteInteger('ProxyEnable',1); WriteString('ProxyServer',Server); // WriteString('ProxyOverride','<local>'); // Usar si hace falta end; finally Free; end; end; EnableProxy('servidor.com:80');
#11
Escrito 09 octubre 2009 - 04:09
Las estructuras que te pasé, sacadas del archivo Wininet.h de Microsoft, no sabía bién como traducirlas a delphi, en concreto, la equivalencia del concepto de "union" de C, que significa que dos o mas variables comparten el mismo espacio de memoria. así que esta es la traducción correcta después de estudiar un poco el delphi:
type INTERNET_PER_CONN_OPTION = record dwOption: DWORD; case integer of 0:(dwValue: DWORD;); 1:(pszValue: LPTSTR;); 2:(ftValue: FILETIME;); end; LPINTERNET_PER_CONN_OPTION = ^INTERNET_PER_CONN_OPTION;
El código que te puse funciona en delphi 6
Saludos.
#12
Escrito 09 octubre 2009 - 04:22
Y esto ¿serviria? :^)
delphi
uses Registry; procedure EnableProxy(Server: String); begin with TRegistry.Create do try RootKey:= HKEY_CURRENT_USER; if OpenKey('Software\Microsoft\Windows\CurrentVersion\Internet Settings',FALSE) then begin WriteInteger('ProxyEnable',1); WriteString('ProxyServer',Server); // WriteString('ProxyOverride','<local>'); // Usar si hace falta end; finally Free; end; end; EnableProxy('servidor.com:80');
Pues a mi entender, si sirve, sólo tiene una pega, no funciona en caliente, al menos a mi. Se debe reabrir el iExplorer para que lea la configuración. Yo siempre lo hice en C con la API porque lo puedes "refrescar" en caliente.
La traducción que he hecho funciona en mis pruebas. Probarlo vosotros y me comentáis.
Saludos.
#13
Escrito 09 octubre 2009 - 04:34
#14
Escrito 09 octubre 2009 - 04:57
He probado tu code escafandra, al parecer en mi caso no funciona , compila bien pero no asigna nada, probé el de seoane, con el IE abierto sin ninguna config y me funcionó.
Vaya, pues me gustaría saber que es lo que pasa. Se me ocurre que quizás el problema está en el parámetro use de la función SetConnectionOptions. En uno de los post la coloqué a false y luego la edite para ponerla a true, esa opción correspondería a la "casilla" "usar un servidor proxy para la LAN..." de las Opciones de Internet->Conexiones->Configuración de LAN.
SetConnectionOptions('proxy.mi.empresa-data.com:8080', '', true);
Por otro lado uso IE 8, aunque el código en C lo he usado en versiones menores que la 7 sin problemas. Y mi S.O. es WindowsXP. Y como dije antes, la modificación del registro que propone seoane no me funciona en caliente, de hecho nunca la he usado por ese problema. ¿Será cosa del S.O.? :^) porque del IE no lo creo.
Saludos.
#15
Escrito 09 octubre 2009 - 05:06
#16
Escrito 09 octubre 2009 - 05:10
Saludos.
#17
Escrito 10 octubre 2009 - 02:39
Al no funcionar igual, mi propuesta con la API InternetSetOption en delphi, en todas las maquinas y al haber tenido que traducir estructuras usadas para su manejo, pensé que podría ser un problema con el unicode. Esas esctruturas tienen versión A y W, al igual que la API InternetSetOptionA y InternetSetOptionW. De esta forma, he forzado a usar la versión InternetSetOptionA. Quizás el problema está en como compila cada versión del delphi por no estar completas las definiciones, y mi torpeza en la traducción de las mismas. A mi me funciona bien (tanto con InternetSetOption como con InternetSetOptionA), con delphi 6 y en Windows XP profesional o Home y con IE desde la versión 6 (no he probado anteriores).
Subo un programa de ejemplo y su fuente. Si tienes la amabilidad, enecumene, o cualquiera de vosotros, de probarlo quizás me saqueis de dudas y pueda entender un poco mejor al delphi y sus correspondencias con C.
Saludos.
#18
Escrito 10 octubre 2009 - 06:07
#19
Escrito 10 octubre 2009 - 06:20
Hola escafandra, acabo de descargar el zip y probé el programa y ahora me funcionó .
Muchas gracias por tomarte la molestia, ya me estaba volviendo loco .
Ahora, si no es pedirte mucho, ¿Podrias hacer la prueba cambiando InternetSetOptionA por InternetSetOption?. De esta forma, si no funciona, sabremos que es un problema del unicode, que tendríamos que tener en cuenta a la hora de realizar otras adaptaciones de APIs a delphi en el futuro.
Saludos.
#20
Escrito 10 octubre 2009 - 02:17