27
Mt.exe The Mt.exe file is a tool that generates signed files and catalogs. It is available in the Microsoft Windows Software Development Kit (SDK). Mt.exe requires that the file referenced in the manifest be present in the same directory as the manifest. Mt.exe generates hashes using the CryptoAPI implementation of the Secure Hash Algorithm (SHA-1). For more information about hash algorithms, see Hash and Signature Algorithms . Hashes are inserted as a hexadecimal string into the file tags in the manifest. The tool currently only generates SHA-1 hashes, although files in manifests may use other hashing schemes. Mt.exe uses Makecat.exe to generate catalog files (.cat) from catalog definition files (.cdf). This tool fills out a standard template CDF with the name and location of your manifest. You can use this with Makecat.exe to generate the assembly catalog. The version of Mt.exe provided in recent versions of the Windows SDK can also be used to generate manifests for managed assemblies and unmanaged side-by-side assemblies. Syntax mt.exe [-manifest<component1.manifest><component2.manifest>] [-identity: <identity string>] [-rgs:<file1.rgs>] [-tlb:<file2.tlb>] [-dll:<file3.dll>] [-replacements:<XML filename>] [-managedassemblyname:<managed assembly>] [-nodependency] [- category] [-out:<output manifest name>] [-inputresource:<file4>;[#]<resource_id>] [-outputresource:<file5>;[#]<resource_id>] [-updateresource:<file6>; [#]<resource_id>] [-hashupdate[:<path to files>]] [-makecdfs] [- validate_manifest] [-validate_file_hashes:<path to files>] [-canonicalize] [- check_for_duplicates] [-nologo] [-verbose] Command Line Options Mt.exe uses the following case-insensitive command line options. Option Description -manifest Specifies the name of the manifest file. To modify a sin name. For example, component.manifest. To merge multiple manifests, specify the names of the so

Como usar el Mt

Embed Size (px)

Citation preview

Page 1: Como usar el Mt

Mt.exeThe Mt.exe file is a tool that generates signed files and catalogs. It is available in the Microsoft Windows Software Development Kit (SDK). Mt.exe requires that the file referenced in the manifest be present in the same directory as the manifest.

Mt.exe generates hashes using the CryptoAPI implementation of the Secure Hash Algorithm (SHA-1). For more information about hash algorithms, see Hash and Signature Algorithms. Hashes are inserted as a hexadecimal string into the file tags in the manifest. The tool currently only generates SHA-1 hashes, although files in manifests may use other hashing schemes.

Mt.exe uses Makecat.exe to generate catalog files (.cat) from catalog definition files (.cdf). This tool fills out a standard template CDF with the name and location of your manifest. You can use this with Makecat.exe to generate the assembly catalog.

The version of Mt.exe provided in recent versions of the Windows SDK can also be used to generate manifests for managed assemblies and unmanaged side-by-side assemblies.

Syntax

mt.exe [-manifest<component1.manifest><component2.manifest>] [-identity: <identity string>] [-rgs:<file1.rgs>] [-tlb:<file2.tlb>] [-dll:<file3.dll>] [-replacements:<XML filename>] [-managedassemblyname:<managed assembly>] [-nodependency] [-category] [-out:<output manifest name>] [-inputresource:<file4>;[#]<resource_id>] [-outputresource:<file5>;[#]<resource_id>] [-updateresource:<file6>;[#]<resource_id>] [-hashupdate[:<path to files>]] [-makecdfs] [-validate_manifest] [-validate_file_hashes:<path to files>] [-canonicalize] [-check_for_duplicates] [-nologo] [-verbose]

Command Line Options

Mt.exe uses the following case-insensitive command line options.

Option Description

-manifest Specifies the name of the manifest file. To modify a single manifest, specify one manifest file name. For example, component.manifest.

To merge multiple manifests, specify the names of the source manifests here. Specify the name of the updated manifest with either theoutputresource, or -updateresource options. For example, the following command line requests an operation that merges two manifests, man1.manifest and man2.manifest, into a new manifest, man3.manifest.

mt.exe -manifest man1.manifest man2.manifest -out:man3.manifest

Note  No colon (:) is required with the -manifest option.

-identity Provides the attributes values of the assemblyIdentity element of the manifest. The argument of thethe attribute values in fields separated by commas. Provide the value of the name attribute in the first field, without including a "name=" substring.

Page 2: Como usar el Mt

All the remaining fields specify the attributes and their values using the form: <attribute name>

For example, to update the assemblyIdentity element of the manifest with the following information:

<assemblyIdentity type="win32" name="Microsoft.Windows.SampleAssembly" version="6.0.0.0" processorArchitecture="x86" publicKeyToken="a5aaf5ba15723d5"/>

include the following -identity option on the command line:

-identity:"Microsoft.Windows.SampleAssembly, processorArchitecture=x86, version=6.0.0.0, type=win32, publicKeyToken=a5aaf5ba15723d5"

-rgs Specifies the name of the registration script (.rgs) file. The -dll option is required to use the

-tlb Specifies the name of the type library (.tlb) file. The -dll option is required to use the

-dll Specifies the name of the dynamic-link library (DLL) file. The -dll option is required byname of the DLL you intend to eventually build from the .rgs or .tlb files.

For example, the following command requests an operation that generates a manifest from .rgs and .tlb files.

mt.exe -rgs:testreg1.rgs -tlb:testlib1.tlb -dll:test.dll -replacements:rep.manifest -identity:"Microsoft.Windows.SampleAssembly, processorArchitecture=x86, version=6.0.0.0, type=win32, publicKeyToken=a5aaf5ba15723d5" -out:rgstlb.manifest

-replacements Specifies the file that contains values for the replaceable string in the .rgs file.

-managedassemblyname

Generates a manifest from the specified managed assembly. Use with the -nodependencyelements. Use with the -category option to generate a manifest with category tags. For example, if managed.dll is a managed assembly, the following command line generates the out.manifest from managed.dll.

mt.exe -managedassemblyname:managed.dll -out:out.manifest

-nodependency Specifies an operation that generates a manifest without dependency elements. The managedassemblyname option. For example, if managed.dll is a managed assembly, the following command line generates the out.manifest from managed.dll without dependency information.

mt.exe -managedassemblyname:managed.dll -out:out.manifest -nodependency

-category Specifies an operation that generates a manifest with category tags. The -category option requires theexample, if managed.dll is a managed assembly, the following command line generates the out.manifest from managed.dll with category tags.

mt.exe -managedassemblyname:managed.dll -out:out.manifest -category

-nologo Specifies an operation that is run without displaying standard Microsoft copyright data. Ifused to prevent writing unwanted information into the log files.

-out Specifies the name of the updated manifest. If this is a single-manifest operation, and the

Page 3: Como usar el Mt

-inputresource Specifies an operation performed on a manifest obtained from a resource of type RT_MANIFEST. If thespecifying the resource identifier, <resource_id>, the operation uses the value CREATEPROCESS_MANIFEST_RESOURCE.

For example, the following command requests an operation that merges a manifest from a DLL, dll_with_manifest.dll, and a manifest file, man2.manifest. The merged manifests are received by a manifest in the resource file of another DLL, dll_with_merged_manifests.

mt.exe -inputresource:dll_with_manifest.dll;#1 -manifest man2.manifest -outputresource:dll_with_merged_manifest.dll;#3

To extract the manifest from a DLL, specify the DLL file name. For example, the following command extracts the manifest from lib1.dll and man3.manifest receives the extracted manifest.

mt.exe -inputresource:lib.dll;#1 -out:man3.manifest

-outputresource Specifies an operation that generates a manifest to be received by a resource of type RT_MANIFEST. If thewithout specifying the resource identifier, <resource_id>, the operation uses the value CREATEPROCESS_MANIFEST_RESOURCE.

-updateresource Specifies an operation that is equivalent to using the -inputresource and -outputresourcefollowing command requests an operation that computes a hash of the files at the specified path and updates the manifest of a resource of a portable executable (PE).

mt.exe -updateresource:dll_with_manifest.dll;#1 -hashupdate:f:\files.

-hashupdate Computes the hash value of the files at the specified paths and updates the value of the

For example, the following command requests an operation that merges two manifest files, man1.manifest and man2.manifest, and updates the value of the hashattribute of the File element in the manifest that receives the merged information, merged.manifest.

mt.exe -manifest man1.manifest man2.manifest -hashupdate:d:\filerepository -out:merged.manifest

If the paths to the files are not specified, the operation searches location of the manifest specified to receive the update. For example, the following command requests an operation that computes the updated hash value using files found by searching the location of updated.manifest.

mt.exe -manifest yourComponent.manifest -hashupdate -out:updated.manifest

-validate_manifest Specifies an operation that performs a syntax check of the conformance of the manifest with the manifest schema. For example, the following command requests a check to validate the conformance of man1.manifest with its schema.

mt.exe -manifest man1.manifest -validate_manifest

-validate_file_hashes Specifies an operation that validates the hash values of the File elements of the manifest. For example, the following command requests an operation that validates the hash values of all the File elements of the man1.manifest.

mt.exe -manifest man1.manifest -validate_file_hashes:"c;\files"

-canonicalize Specifies an operation to update the manifest to canonical form. For example, the following command updates man1.manifest to canonical form.

mt.exe -manifest man1.manifest

-check_for_duplicates Specifies an operation that checks the manifest for duplicate elements. For example, the following command checks man1.manifest for duplicate

Page 4: Como usar el Mt

elements.

mt.exe -man1.manifest -check_for_duplicates

-makecdfs Generates .cdf files to make catalogs. For example, to the following command requests an operation that updates the hash value and generates a .cdf file.

mt.exe -manifest comp1.manifest -hashupdate -makecdfs -out:updated.manifest

-verbose Displays verbose debugging information.

-? When run with -?, or with no options and arguments, Mt.exe displays help text.

 

Related topics

Side-by-Side Assembly Development Tools

 

 

Build date: 9/5/2012

TRADUCCIÓN

Page 5: Como usar el Mt

Mt.exe 12 de los 37 ha calificado este útil - Valorar este tema

El archivo Mt.exe es una herramienta que genera archivos firmados y catálogos. Está disponible en el Microsoft Windows Software Development Kit (SDK). Mt.exe requiere que el archivo de referencia en el manifiesto estar presente en el mismo directorio que el manifiesto.

Mt.exe genera hashes utilizando la implementación de CryptoAPI del Secure Hash Algorithm (SHA-1). Para obtener más información acerca de los algoritmos hash, ver Hash y algoritmos de firma . Los valores hash se insertan como una cadena hexadecimal en las etiquetas de archivo en el manifiesto. Actualmente, la herramienta sólo genera hashes SHA-1, aunque los archivos de manifiestos pueden utilizar otros esquemas de hash.

Mt.exe Makecat.exe utiliza para generar archivos de catálogo (. Cat) de archivos de definición de catálogo (. Cdf). Esta herramienta rellena una plantilla estándar CDF con el nombre y la ubicación del manifiesto. Usted puede usar esto con Makecat.exe para generar el catálogo de montaje.

La versión de Mt.exe suministran en versiones recientes del SDK de Windows también se puede utilizar para generar manifiestos de los ensamblados administrados y no administrados lado a lado asambleas.

Sintaxis

mt.exe [-manifest<component1.manifest><component2.manifest>] [-identity: <identity string>] [-rgs:<file1.rgs>] [-tlb:<file2.tlb>] [-dll:<file3.dll>] [-replacements:<XML filename>] [-managedassemblyname:<managed assembly>] [-nodependency] [-category] [-out:<output manifest name>] [-inputresource:<file4>;[#]<resource_id>] [-outputresource:<file5>;[#]<resource_id>] [-updateresource:<file6>;[#]<resource_id>] [-hashupdate[:<path to files>]] [-makecdfs] [-validate_manifest] [-validate_file_hashes:<path to files>] [-canonicalize] [-check_for_duplicates] [-nologo] [-verbose]

Opciones de línea de comandos

Mt.exe utiliza los siguientes mayúsculas y minúsculas opciones de línea de comandos.

Opción Descripción-Manifiesto Especifica el nombre del archivo de manifiesto. Para modificar un

manifiesto único, especifique un nombre de archivo de manifiesto.

Page 6: Como usar el Mt

Por ejemplo, component.manifest.

Para combinar múltiples manifiestos, especifique los nombres de la fuente se manifiesta aquí. Especifique el nombre del manifiesto de actualización, ya sea con el-out,-outputresource o UpdateResource opciones. Por ejemplo, las solicitudes de línea de comandos siguientes una operación que combina dos manifiestos, man1.manifest y man2.manifest, en un nuevo manifiesto, man3.manifest.

mt.exe-manifiesto man1.manifest man2.manifest Salida: man3.manifest

Nota n puntos (:) se requiere con la opción del manifiesto.

-Identidad

Proporciona los valores de los atributos del elemento assemblyIdentity del manifiesto. El argumento de la opción-identidad es un valor de cadena que contiene los valores de los atributos en campos separados por comas. Proporcionar el valor del atributo de nombre en el primer campo, sin incluir un "name =" subcadena. Todos los campos restantes especifican los atributos y sus valores utilizando el formato: <nombre atributo> = <attribute_value>.

Por ejemplo, para actualizar el elemento assemblyIdentity del manifiesto con la siguiente información:

<assemblyIdentity type="win32" name="Microsoft.Windows.SampleAssembly" version="6.0.0.0" processorArchitecture="x86" publicKeyToken="a5aaf5ba15723d5"/>

incluir la siguiente opción de la identidad en la línea de comandos:

-Identidad: "Microsoft.Windows.SampleAssembly, processorArchitecture versión x86 =, = 6.0.0.0, type = win32, publicKeyToken = a5aaf5ba15723d5"

-RgsEspecifica el nombre de la secuencia de registro (. Rgs) archivo. La dll-opción es necesaria para utilizar la opción-rgs opción.

-TlbEspecifica el nombre de la biblioteca de tipos (. Tlb). La opción dll-es necesario para utilizar la opción-tlb.

-Dll Especifica el nombre de la biblioteca de vínculos dinámicos (DLL). La dll-opción es requerida por mt.exe si los RGS-o-TLB opciones se utilizan. Especifique el nombre del archivo DLL tiene la intención de construir con el tiempo de las CCAA. O. Tlb.

Por ejemplo, las solicitudes de comando después de una operación

Page 7: Como usar el Mt

que genera un manifiesto de. Rgs y. Tlb.

mt.exe-rgs: testreg1.rgs-tlb: testlib1.tlb-dll: test.dll-reemplazos: identidad rep.manifest-: "Microsoft.Windows.SampleAssembly, processorArchitecture versión x86 =, = 6.0.0.0, type = win32 , publicKeyToken a5aaf5ba15723d5 = "Salida: rgstlb.manifest

-ReemplazosEspecifica el archivo que contiene los valores para la cadena reemplazable en el archivo. Rgs.

-Managedassemblyname

Genera un manifiesto del ensamblado administrado especificado. Usar con la opción-nodependency para generar un manifiesto sin elementos de dependencia. Usar con opción de la categoría-para generar un manifiesto con las etiquetas de categoría. Por ejemplo, si managed.dll es un ensamblado administrado, la línea de comandos siguiente genera el out.manifest de managed.dll.

mt.exe-managedassemblyname: managed.dll Salida: out.manifest

-Nodependency

Especifica una operación que genera un manifiesto sin elementos de dependencia. El nodependency-opción requiere la opción-managedassemblyname. Por ejemplo, si managed.dll es un ensamblado administrado, la siguiente línea de comandos genera el out.manifest de managed.dll sin información de dependencia.

mt.exe-managedassemblyname: managed.dll Salida: out.manifest-nodependency

-Categoría

Especifica una operación que genera un manifiesto con etiquetas de categoría. La categoría con opción requiere la opción-managedassemblyname. Por ejemplo, si managed.dll es un ensamblado administrado, la siguiente línea de comandos genera el out.manifest de managed.dll con etiquetas de categoría.

mt.exe-managedassemblyname: managed.dll Salida: out.manifest-categoría

-Nologo

Especifica una operación que se ejecuta sin mostrar datos estándar de Microsoft de autor. Si mt.exe se ejecuta como parte de un proceso de construcción, esta opción se puede utilizar para evitar escribir la información deseada en los archivos de registro.

SalidaEspecifica el nombre del manifiesto actualizada. Si esta es una operación de un solo manifiesto, y la Salida opción se omite, el manifiesto original es modificado.

-Inputresource Especifica una operación realizada en un manifiesto obtenido a partir de un recurso de RT_MANIFEST tipo. Si la opción inputresource-se utiliza sin especificar el identificador de recursos, <resource_id>, la operación utiliza el

Page 8: Como usar el Mt

CREATEPROCESS_MANIFEST_RESOURCE valor.

Por ejemplo, el comando siguiente se solicita una operación que combina un manifiesto a partir de un archivo DLL, dll_with_manifest.dll, y un archivo de manifiesto, man2.manifest. Los manifiestos combinadas son recibidas por un manifiesto en el archivo de recursos de otro archivo DLL, dll_with_merged_manifests.

mt.exe-inputresource: dll_with_manifest.dll; # 1-manifiesta-man2.manifest outputresource: dll_with_merged_manifest.dll; # 3

Para extraer el manifiesto desde un archivo DLL, especifique el nombre del archivo DLL. Por ejemplo, el siguiente comando extrae el manifiesto de lib1.dll y man3.manifest recibe el manifiesto extraído.

mt.exe-inputresource: lib.dll; # 1-Salida: man3.manifest

-Outputresource

Especifica una operación que genera un manifiesto para ser recibido por un recurso de RT_MANIFEST tipo. Si la opción outputresource-se utiliza sin especificar el identificador de recursos, <resource_id>, la operación utiliza el CREATEPROCESS_MANIFEST_RESOURCE valor.

-UpdateResource

Especifica una operación que es equivalente a usar la inputresource-and-outputresource opciones con idénticos argumentos. Por ejemplo, el comando siguiente se solicita una operación que calcula un hash de los archivos en la ruta especificada y actualiza el manifiesto de un recurso de un archivo ejecutable portable (PE).

mt.exe-UpdateResource: dll_with_manifest.dll; # 1-hashupdate: f: \ archivos.

-Hashupdate Calcula el valor hash de los archivos en las rutas especificadas y actualiza el valor del atributo hash del elemento del archivo con este valor.

Por ejemplo, el comando siguiente se solicita una operación que combina dos archivos de manifiesto, man1.manifest y man2.manifest, y actualiza el valor del atributo hash del elemento del archivo en el manifiesto que recibe la información resultante de la fusión, merged.manifest.

mt.exe-manifiesto man1.manifest man2.manifest-hashupdate: d: \ FileRepository Salida: merged.manifest

Page 9: Como usar el Mt

Si las rutas de acceso a los archivos no se especifica, la operación busca ubicación del manifiesto especificado para recibir la actualización. Por ejemplo, las solicitudes de comando después de una operación que calcula el valor de hash actualizado usando los archivos encontrados por buscar la ubicación de updated.manifest.

mt.exe-manifiesto-yourComponent.manifest hashupdate Salida: updated.manifest

-Validate_manifest

Especifica una operación que se realiza una comprobación de sintaxis de la conformidad del manifiesto con el esquema de manifiesto. Por ejemplo, el comando siguiente se solicita una verificación para validar el cumplimiento de man1.manifest con su esquema.

mt.exe-manifiesto-man1.manifest validate_manifest

-Validate_file_hashes

Especifica una operación que valida los valores hash de los elementos del archivo de manifiesto. Por ejemplo, el comando siguiente se solicita una operación que valida los valores hash de todos los elementos del archivo de la man1.manifest.

mt.exe-manifiesto-man1.manifest validate_file_hashes: "c \ archivos;"

-Canonicalize

Especifica una operación para actualizar el manifiesto con la forma canónica. Por ejemplo, el siguiente comando actualiza man1.manifest a la forma canónica.

mt.exe-manifiesto man1.manifest

-Check_for_duplicates

Especifica una operación que verifica el manifiesto de elementos duplicados. Por ejemplo, el siguiente comando comprueba man1.manifest para los elementos duplicados.

mt.exe-man1.manifest-check_for_duplicates

-Makecdfs

Genera. Archivos CDF para hacer catálogos. Por ejemplo, para las solicitudes de comando después de una operación que actualiza el valor hash y genera un archivo. Cdf.

mt.exe-manifiesto-comp1.manifest hashupdate-makecdfs Salida: updated.manifest

-Verbose Muestra información de depuración detallada.

-?Cuando se ejecuta con - o sin opciones y argumentos, muestra Mt.exe texto de ayuda.

Temas relacionados

Page 10: Como usar el Mt

Side-by-Side Herramientas de montaje de Desarrollo

Fecha de producción: 09/05/2012

http://blogs.msdn.com/b/calvin_hsia/archive/2007/04/13/add-a-manifest-to-control-your-application-vista-uac-behavior.aspx

Add a manifest to control your application Vista UAC behavior

CalvinH 13 Apr 2007 5:29 PM

13

Try this on Windows XP or Vista (I don’t remember if manifests are allowed on Win2000: can someone confirm please? Thanks) Start Notepad, then choose File->Open and navigate to c:\windows\system32\notepad.exe and click Open. Hit Ctrl-F to find the text “assembly”You’ve now found the embedded XML manifest file. Try the same with VFP9.EXE, then an EXE that you have built with VFP9 On XP, this manifest can specify additional dependencies. For VFP9, it indicates which version of Windows Common Controls to use. For an EXE that VFP built the manifest is the same as VFPs. On Vista, this manifest can further specify security requirements for an application.For example, on Vista, applications are not allowed to write into “Program Files” or Windows directories. Similarly with the registry. Some applications will attempt to write these. If there is no requestedExecutionLevel, then the registry and file virtualization will be turned on. The program “thinks” it’s writing to “Program Files”, but it’s really writing to C:\Users\<username>\AppData\Local\VirtualStore\Program Files. The registry redirects HKEY_LOCAL_MACHINE\Software to HKEY_CURRENT_USER\Software\Classes\VirtualStore\MACHINE\SOFTWARE\<Application Registry Keys>

Page 11: Como usar el Mt

You can further control Vista UAC settings by running secpol.msc and navigating to Local Security Settings->Local Policies->Security Options Try this on Vista: Start->Run->Cmd. Try to write a file to Program Files or Windows directories-> “Access Denied” The MT.EXE tool that ships with Visual Studio or the Vista SDK can allow you to embed a manifest as a Windows Resource in an EXE file. Historically, only a Linker could build and manipulate a Windows Resource. Starting with Windows NT, the resources could be manipulated from within a program using the BeginUpdateResource family of functions. Foxpro EXE files have been built the same way for about 18 years: using a Fox resource architecture. There is a stub loader, and 0 or more sections (such as the .APP) physically appended to the file. Windows tools that manipulate the EXE file format do not pay attention to any data appended to an EXE file, so when these tools write out the result, they do not write out any additional data. With no APP, the loader merely puts up a File->Open dialog requesting an APP to run. These Windows Tools use the BeginUpdateResource family of functions, but Foxpro could not, because it still had to run on Windows 95 as well as NT Starting with VFP8 (I think) VFP was able to add a generated Type Library as a Windows Resource inside a DLL, using the BeginUpdateResource functions. Now you know why this feature doesn’t work on Win 95. Start Task Manager on Windows Vista, choose the Processes tab, choose View->Select Columns->Virtualization.You will see that some processes have virtualization Enabled, Disabled, or nothing at all (depending on the privileges of the launcher) in that column. Save this code as TestVista.Prg and run it  IF _vfp.StartMode>0     && If we're running as an EXE      MESSAGEBOX("Look at Task Pane Virtualization column for TestVista")      RETURN ENDIF BUILD PROJECT TestVista FROM TestVistaBUILD EXE TestVista FROM TestVista!/n TestVista     RETURN  It builds an EXE that will show a MessageBox and then runs it. With the MessageBox showing, look at the Task Manager. The Virtualization is Enabled. Now run this line from a VS Command prompt (Start->All Programs->Microsoft Visual Studio->Visual Studio Tools->VS Command prompt) in the same directory mt -manifest TestVista.Exe.Manifest -outputresource: TestVista.exe;#1

Page 12: Como usar el Mt

Then run the TestVista.Exe. The Open File dialog shows up requesting an APP to run. Now the Virtualization is blank. The sample below shows how to create a simple project hook that allows you to embed any file as a manifest. Try running it on Vista, with various values of requestedExecutionLevel. For more about Vista User Account Control and manifests, see

         Registry Virtualization         http://download.microsoft.com/download/5/6/a/56a0ed11-e073-42f9-932b-

38acd478f46d/WindowsVistaUACDevReqs.doc         The Windows Vista Developer Story: Windows Vista Application Development

Requirements for User Account Control (UAC)         Manifest Resources         Creating a Manifest for Your Application          For another example of project hooks and modifying the VFP built EXE/DLL, see

Calvin Hsia 's WebLog : Strongly typed methods and properties (Another way to see a manifest: Using Visual Studio, you can chose File->Open->File to open an Executable. The default is to open it with the Resource Editor.There’s a little down arrow that you can choose on the File->Open dialog so that you can choose to open the file using a different tool, such as the Binary Editor.In the resource view, you can see the Manifest file of an executable.) The sample code below creates a manifest and creates a project hook that will embed a manifest file CLEAR IF _vfp.StartMode>0     && If we're running as an EXE      MESSAGEBOX("Look at Task Pane Virtualization column for TestVista")      RETURN ENDIF MODIFY COMMAND PROGRAM() nowait#if .t.BUILD PROJECT TestVista FROM TestVistaBUILD EXE TestVista FROM TestVista!/n TestVista     RETURN#endif   CLEAR ALLCLEARIF LOWER(JUSTFNAME(PROGRAM()))!="testvista"      ?"This sample file must be called TestVista"      RETURN ENDIF

Page 13: Como usar el Mt

#if .f.      To use with your project, you only need the projecthook class#endif SET SAFETY off IF FILE("TestVista.Exe")      DELETE FILE TestVista.ExeENDIF fAddManifest=.t.IF !FILE("TestVista.pjx")      BUILD PROJECT TestVista FROM TestVistaENDIF MODIFY PROJECT TestVista NOWAIT IF fAddManifest      *cExLevel="highestAvailable"      cExLevel="asInvoker"*     cExLevel="requireAdministrator"      TEXT TO cXML  TEXTMERGE              <?xml version="1.0" encoding="UTF-8" standalone="yes"?>            <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">                   <assemblyIdentity version="1.0.0.0" processorArchitecture="X86" name="CalvinsDemo" type="win32"/>            <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">                        <security>                              <requestedPrivileges>                                    <requestedExecutionLevel level="<<cExLevel>>" />                               </requestedPrivileges>                        </security>                  </trustInfo>                  <dependency>                      <dependentAssembly>                          <assemblyIdentity                              type="win32"                              name="Microsoft.Windows.Common-Controls"                              version="6.0.0.0"                              language="*"                              processorArchitecture="x86"                              publicKeyToken="6595b64144ccf1df"                          />                      </dependentAssembly>                  </dependency>            </assembly>      ENDTEXT      STRTOFILE(cXML,"TestVista.Exe.xml")      _vfp.ActiveProject.ProjectHook = NEWOBJECT('MFestPHook')    && use projecthook to modify typelibrary if necessaryENDIF BUILD EXE TestVista FROM TestVista_vfp.ActiveProject.Close *Now test it. Try running it from Windows Explorer or a CMD prompt!/n TestVista#define RT_MANIFEST 24  && from winuser.h#define FOX_SIG 33536

Page 14: Como usar el Mt

 DEFINE CLASS MFestPHook AS ProjectHook      PROCEDURE AfterBuild(nError)            IF nError=0                  ExeName=JUSTSTEM(_vfp.ActiveProject.Name)+".Exe"                  MFest=ExeName+".xml"                  IF FILE(MFest)    && if a manifest exists                        strMFest=FILETOSTR(MFest)     && read in the manifest into a string                        DIMENSION asec[1] && preserve 2 sections of EXE                        nSects=0                        h=FOPEN(ExeName)                        fpos=FSEEK(h,0,2) && go to EOF                        FOR i = 1 TO 20                              FSEEK(h,fpos-14,0)                              pmt=FREAD(h,14)                              sig=BITAND(CTOBIN(SUBSTR(pmt,1,2),"2sr") ,0xffff)                              sz=CTOBIN(SUBSTR(pmt,11,4),"4sr")*                             ?i,sz,sig,TRANSFORM(sig,"@0x")                              IF sig != FOX_SIG                                    nSects = i-1                                    EXIT                               ENDIF                               FSEEK(h,fpos-sz,0)                              DIMENSION  asec[i]                              asec[i]=FREAD(h,sz)                              fpos = fpos - sz                        ENDFOR                         FCLOSE(h)                        DECLARE integer BeginUpdateResource IN WIN32API string , integer                        DECLARE integer EndUpdateResource IN WIN32API integer, integer                        DECLARE integer UpdateResource IN WIN32API integer,integer,integer,integer, string, integer                        DECLARE Integer GetLastError IN win32api                        h=BeginUpdateResource(ExeName,0)                        IF h =0                              ?"Err=",GetLastError()                        ELSE                               UpdateResource(h,RT_MANIFEST,1,0x409,0,0) && del existing one, if any                              UpdateResource(h,RT_MANIFEST,1,0x409,strMFest+CHR(0),LEN(strMFest))                              IF EndUpdateResource(h,0)=0                                    ?"Err=",GetLastError()                              ENDIF                               h=FOPEN(ExeName,2)                              fpos=FSEEK(h,0,2)                              FOR i = 1 TO nSects                                    FWRITE(h,asec[i])                              ENDFOR                               FCLOSE(h)                        ENDIF                         ?"Added manifest"                  ENDIF

Page 15: Como usar el Mt

            ENDIF ENDDEFINE  235882

Añadir un manifiesto para controlar su aplicación Vista comportamiento UAC

CalvinH 13 de abril 2007 17:29

13

Pruebe esto en Windows XP o Vista (no recuerdo si se manifiesta son permitidos en Win2000: ¿Puede alguien confirmar por favor gracias) Inicie el Bloc de notas y, a continuación seleccione Archivo-> Abrir y vaya a C: \ windows \ system32 \ notepad.exe y haga clic en Abrir. Presiona Ctrl-F para buscar el texto " assembly " Ahora usted ha encontrado el archivo de manifiesto XML incrustado. Intente lo mismo con VFP9.EXE, a continuación, un archivo EXE que se ha construido con VFP9 En XP, este manifiesto puede especificar dependencias adicionales. Para VFP9, indica la versión de Common Windows Controles de usar. Para un EXE que VFP construido el manifiesto es el mismo que VFPs. En Vista, este manifiesto además puede especificar requisitos de seguridad para una aplicación. Por ejemplo, en Windows Vista, las aplicaciones no pueden escribir en "Archivos de programa" o los directorios de Windows. Lo mismo ocurre con el registro. Algunas aplicaciones intentan escribir estos. Si no hay requestedExecutionLevel, entonces el registro y archivo de virtualización se encenderá. El programa "piensa" que está escribiendo en "Archivos de programa", pero

Page 16: Como usar el Mt

está realmente escrito en C: \ Users \ <nombre de usuario> \ AppData \ Local \ VirtualStore \ Program Files. El registro redirecciona HKEY_LOCAL_MACHINE \ Software a HKEY_CURRENT_USER \ Software \ Classes \ MACHINE VirtualStore \ \ SOFTWARE \ <Teclas Registro <Application Además, usted puede controlar la configuración de UAC de Vista ejecutando secpol.msc y navegando hasta Seguridad Local Settings-> Directivas locales-> Opciones de seguridad Pruebe esto en Vista: Inicio-> Ejecutar-> cmd. Trate de escribir un archivo en Archivos de programa o Windows "Acceso denegado" los directorios-> La herramienta Mt.exe que se incluye con Visual Studio o el SDK de Windows Vista puede permitir incrustar un manifiesto como un recurso de Windows en un archivo EXE. Históricamente, sólo un vinculador puede construir y manipular un recurso de Windows. A partir de Windows NT, los recursos podrían ser manipulado desde un programa mediante el BeginUpdateResource familia de funciones. Los archivos de FoxPro EXE se han construido de la misma manera durante unos 18 años: el uso de una arquitectura de recursos Fox. Hay un cargador de talón, y 0 o más secciones (tales como la APP.) Físicamente añade al archivo. Herramientas de Windows para manipular el formato de archivo EXE no se presta atención a los datos adjuntos a un archivo EXE, por lo que cuando estas herramientas escribir el resultado, no escribir ningún dato adicional. Sin APP, el cargador simplemente pone un Archivo-> Abrir diálogo solicitando una APP para correr. Estas herramientas de Windows utiliza el BeginUpdateResource familia de funciones, pero Foxpro no podía, porque todavía tenía que correr en Windows 95 y NT A partir de VFP8 (creo) VFP fue capaz de añadir una biblioteca de tipos generada como de recursos de Windows dentro de una DLL, utilizando las funciones BeginUpdateResource. Ahora sabes por qué esta característica no funciona en Windows 95. Iniciar el Administrador de tareas en Windows Vista, seleccione la ficha Procesos, seleccione Ver-> Columnas-> Seleccionar virtualización. Verás que algunos procesos han permitido a la virtualización, discapacitados, o nada en absoluto (en función de los privilegios del lanzador) en esa columna. Guarde este código como TestVista.Prg y ejecutarlo SI _VFP. StartMode> 0 && Si está ejecutando como un EXE       MESSAGEBOX ("Mira columna Virtualización del panel de tareas para TestVista")       REGRESAR ENDIF PROYECTO DE BUILD TestVista TestVista BUILD EXE TestVista DE TestVista ! / N TestVista

Page 17: Como usar el Mt

REGRESAR Se construye un archivo EXE que se mostrará un cuadro de mensaje y luego lo ejecuta. Con la proyección de mensajes, ver el Administrador de tareas. La virtualización está habilitado. Ahora ejecuta esta línea desde el intérprete de comandos de VS (Inicio-> Todos los programas-> Microsoft Visual Studio-> Visual Studio Tools-> VS Símbolo del sistema) en el mismo directorio mt-manifiesta-TestVista.Exe.Manifest outputresource: TestVista.exe; # 1 A continuación, ejecute el TestVista.Exe. El cuadro de diálogo Abrir archivo aparece solicitando una APP para correr. Ahora, la virtualización está en blanco. El siguiente ejemplo muestra cómo crear un proyecto gancho simple que le permite incluir cualquier archivo como un manifiesto. Intente ejecutarlo en Vista, con distintos valores de requestedExecutionLevel. Para más información sobre el Control de cuentas de usuario Vista y manifiestos, ver

         La virtualización del Registro         

         Los desarrolladores de Windows Vista Story: Windows Vista Requisitos de desarrollo de aplicaciones para el Control de cuentas de usuario (UAC)

         Recursos Manifest          Creación de un manifiesto para su aplicación          Para otro ejemplo de ganchos de los proyectos y la modificación de la VFP

construido EXE / DLL, vea Calvin Hsia 's Weblog: Los métodos de establecimiento inflexible de tipos y propiedades

(Otra manera de ver el manifiesto: El uso de Visual Studio, puede elegir Archivo-> Abrir-> Archivo para abrir un ejecutable El valor predeterminado es abrirlo con el Editor de recursos.. Hay una pequeña flecha hacia abajo que se puede elegir en el menú Archivo-> Abrir diálogo de modo que usted puede elegir entre abrir el archivo usando una herramienta diferente, como el Editor binario. En la vista de recursos, se puede ver el archivo de manifiesto de un ejecutable.) El código de ejemplo siguiente crea un manifiesto y crea un gancho proyecto que va a incrustar un archivo de manifiesto CLEAR SI _VFP. StartMode> 0 && Si está ejecutando como un EXE

Page 18: Como usar el Mt

      MESSAGEBOX ("Mira columna Virtualización del panel de tareas para TestVista")       REGRESAR ENDIF MODIFY COMMAND PROGRAM () nowait # If. T. PROYECTO DE BUILD TestVista TestVista BUILD EXE TestVista DE TestVista ! / N TestVista REGRESAR # Endif BORRAR TODO CLEAR IF LOWER (JUSTFNAME (PROGRAMA ()))! = "Testvista" ? "Este archivo muestra debe ser llamado TestVista"       REGRESAR ENDIF # If. F.       Para utilizar con el proyecto, sólo necesita la clase ProjectHook # Endif SET DE SEGURIDAD off IF FILE ("TestVista.Exe")       DELETE FILE TestVista. Exe ENDIF fAddManifest =. t. SI! FILE ("TestVista.pjx")       PROYECTO DE BUILD TestVista TestVista ENDIF MODIFY PROJECT NOWAIT TestVista FAddManifest SI       * CExLevel = "highestAvailable"       cExLevel = "asInvoker" * CExLevel = "requireAdministrator"       TEXTO A cXML TEXTMERGE             <? Xml version = "1.0" encoding = "UTF-8" standalone = "yes"> ensamblado> xmlns="urn:schemas-microsoft-com:asm.v1"

manifestVersion="1.0"> versión <assemblyIdentity ="1.0.0.0" nombre processorArchitecture="X86" ="CalvinsDemo" tipo ="win32"/> <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3"> <security> <requestedPrivileges> <Nivel requestedExecutionLevel = "<< >> cExLevel" /> </ RequestedPrivileges> </ Security> </ TrustInfo> <dependency> <dependentAssembly> <AssemblyIdentity                               type = "win32"                               name = "Microsoft.Windows.Common-Controls"                               version = "6.0.0.0" language = "*" processorArchitecture = "x86" publicKeyToken = "6595b64144ccf1df" />

Page 19: Como usar el Mt

</ DependentAssembly> </ Dependency> </ Assembly>       ENDTEXT STRTOFILE (cXML ", TestVista.Exe.xml")       _VFP. ActiveProject. ProjectHook = NEWOBJECT ('MFestPHook') && ProjectHook utilizar para modificar librería de tipos si es necesario ENDIF BUILD EXE TestVista DE TestVista _VFP. ActiveProject. Cerrar * Ahora probarlo. Intente ejecutarlo desde el Explorador de Windows o un sistema CMD ! / N TestVista # Define RT_MANIFEST 24 && de winuser.h # Define FOX_SIG 33536 DEFINE CLASS MFestPHook COMO ProjectHook PROCEDIMIENTO AfterBuild (nError)             SI nError = 0 EXEName = JUSTSTEM (_VFP. ActiveProject. Nombre) + ". Exe" MFest = EXEName + ". Xml"                   Si el archivo MFest () && si existe un manifiesto                         strMFest = FILETOSTR (MFest) && lee en el manifiesto en una cadena                         DIMENSIÓN ASEC [1] && preservar 2 secciones de EXE                         nSects = 0 h = fopen (EXEName) FPO = fseek (h, 0,2) && ir a FDF                         FOR i = 1 TO 20                               FSEEK (h, FPOs-14, 0) PMT = fread (h, 14) sig = BITAND (CTOBIN (SUBSTR (pmt, 1,2), "2SR"), 0xffff) Conéctate con CTOBIN (SUBSTR (pmt, 11,4) ", 4SR") *? I, sz, sig, TRANSFORM (sig, "@ 0x")                               SI sig! = FOX_SIG nSects = i-1                                     SALIR ENDIF FSEEK (h, FPO-sz, 0)                               DIMENSION asec [i] asec [i] = fread (h, sz) = FPO FPO - sz                         ENDFOR FCLOSE (h)                         DECLARE INTEGER en BeginUpdateResource WIN32API cadena, un entero DECLARE INTEGER en EndUpdateResource WIN32API entero, entero DECLARE INTEGER en UpdateResource WIN32API entero, número entero, número entero, número entero, cadena, un entero DECLARAR EN Integer GetLastError win32api h = BeginUpdateResource (EXEName, 0)                         Si H = 0 ? "Err =", GetLastError ()                         ELSE                               UpdateResource (h, RT_MANIFEST, 1,0 X409,

0,0) && uno del existente, en su caso

Page 20: Como usar el Mt

                              UpdateResource (h, RT_MANIFEST, 1,0 X409,

strMFest + CHR (0), LEN (strMFest))                               SI EndUpdateResource (h, 0) = 0 ? "Err =", GetLastError ()                               ENDIF                               h = fopen (EXEName, 2) FPO FSEEK = (h, 0,2)                               FOR i = 1 TO nSects                                     FWRITE (h, asec [i])                               ENDFOR FCLOSE (h)                         ENDIF                         ? "Alta manifiesto"                   ENDIF ENDIF ENDDEFINE 235882