기본 콘텐츠로 건너뛰기

How To Find the Path and Version of an Office Application from Visual C++

■ jwFreeNote_01

How To Find the Path and Version of an Office Application from Visual C++

Article ID : 247985
Last Review : June 30, 2004
Revision : 1.0
This article was previously published under Q247985

SUMMARY

This article explains how you can examine the registry at run time to determine the installation path and version of an Office application.

MORE INFORMATION

Each Office application is associated with a version independent ProgID and a CLSID. You can examine the registry for keys containing a server's CLSID and ProgID to determine both the installation path and version of the server application.

??/TD> The path to the server application can be found at:
HKEY_CLASSES_ROOT\CLSID\{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx}\LocalServer32
      
where {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx} represents the the CLSID of the server.
??/TD> Likewise, the version dependent ProgID for the registered version for the server application is located at:
HKEY_CLASSES_ROOT\sss.sss\CurVer
      
where sss.sss represents the version independent ProgID of the server.

Steps to Create Sample

1. Create an MFC Appwizard EXE named OfficePath. In step 1 of AppWizard, select Dialog Based and click Finish.
2. Click the Resources tab and open the IDD_OFFICEPATH_DIALOG dialog box.
3. Remove the OK and Cancel Buttons on the dialog box.
4. Add an EditBox to the dialog box and name it IDC_PROGID.
5. Add two CommandButtons to the dialog box. Name the CommandButtons IDPATH and IDVERSION and set the captions to GetPath and GetVersion respectively.
6. Start ClassWizard.
7. Add a function handler to the BN_CLICKED message of each CommandButton.
8. Create a member variable for the EditBox IDC_PROGID. Name the member variable m_ProgID and specify Control for the category and CEdit for the variable type.
9. Close the ClassWizard.
10. In the OfficePathDlg.h file, add the following public member functions to the COfficePathDlg class:
  static BOOL GetPath(LPOLESTR szApp, LPSTR szPath, ULONG cSize);
  static BOOL GetVersion(LPCTSTR szApp, LPSTR szVersion, ULONG cSize);
11. Add the following function definitions to OfficePathDlg.cpp:
void COfficePathDlg::OnPath()
{
    LPOLESTR szwApp;
    char szLocation[255], szApp[50];

    // Get ProgID from EditBox
    m_ProgID.GetWindowText(szApp, 50);
    if (strcmp(szApp,"") == 0)
    {
    MessageBox("Type ProgID in EditBox", "Error");
    return;
    }
    // Find number ofcharacters to be allocated
    int len = strlen(szApp) + 1;

    // Use OLE Allocator to allocate memory
    szwApp = (LPOLESTR) CoTaskMemAlloc(len*2);
    if (szwApp == NULL)
    {
    MessageBox("Out of Memory", "Error");
    return;
    }

    //    AnsiToUnicode conversion
    if (0 == MultiByteToWideChar(CP_ACP, 0, szApp, len,
             szwApp, len))
    {
       // Free Memory allocated to szwApp if conversion failed
       CoTaskMemFree(szwApp);
       szwApp = NULL;
       MessageBox("Error in Conversion", "Error");
       return;
    }

    // Get Path to Application and display it
    if (!GetPath(szwApp, szLocation, 255))
    MessageBox("Error Getting Path", "Error");
    else
    MessageBox(szLocation, "Path");
}

void COfficePathDlg::OnVersion()
{
    CHAR szVersion[255], szApp[50];
    // Get Version of Application
    m_ProgID.GetWindowText(szApp, 50);

    if (strcmp(szApp,"") == 0)
    {
    MessageBox("Type ProgID in EditBox", "Error");
    return;
    }

    // Get Version and display it
    if (!GetVersion(szApp, szVersion, 255))
      MessageBox("Error Getting Version", "Error");

    else
    MessageBox(szVersion, "Version");
}

BOOL COfficePathDlg::GetPath(LPOLESTR szApp, LPSTR szPath, ULONG cSize)
{
    CLSID clsid;
    LPOLESTR pwszClsid;
    CHAR  szKey[128];
    CHAR  szCLSID[60];
    HKEY hKey;

    // szPath must be at least 255 char in size
    if (cSize < 255)
    return FALSE;

    // Get the CLSID using ProgID
    HRESULT hr = CLSIDFromProgID(szApp, &clsid);
    if (FAILED(hr))
    {
    AfxMessageBox("Could not get CLSID from ProgID, Make sure ProgID is correct", MB_OK, 0);
        return FALSE;
    }

    // Convert CLSID to String
    hr = StringFromCLSID(clsid, &pwszClsid);
    if (FAILED(hr))
    {
    AfxMessageBox("Could not convert CLSID to String", MB_OK, 0);
        return FALSE;
    }

    // Convert result to ANSI
    WideCharToMultiByte(CP_ACP, 0, pwszClsid, -1, szCLSID, 60, NULL, NULL);

    // Free memory used by StringFromCLSID
    CoTaskMemFree(pwszClsid);

    // Format Registry Key string
    wsprintf(szKey, "CLSID\\%s\\LocalServer32", szCLSID);

    // Open key to find path of application
    LONG lRet = RegOpenKeyEx(HKEY_CLASSES_ROOT, szKey, 0, KEY_ALL_ACCESS, &hKey);
    if (lRet != ERROR_SUCCESS)
    {
    // If LocalServer32 does not work, try with LocalServer
        wsprintf(szKey, "CLSID\\%s\\LocalServer", szCLSID);
        lRet = RegOpenKeyEx(HKEY_CLASSES_ROOT, szKey, 0, KEY_ALL_ACCESS, &hKey);
    if (lRet != ERROR_SUCCESS)
        {
            AfxMessageBox("No LocalServer Key found!!", MB_OK, 0);
            return FALSE;
        }
    }

    // Query value of key to get Path and close the key
    lRet = RegQueryValueEx(hKey, NULL, NULL, NULL, (BYTE*)szPath, &cSize);
    RegCloseKey(hKey);
    if (lRet != ERROR_SUCCESS)
    {
    AfxMessageBox("Error trying to query for path", MB_OK, 0);
        return FALSE;
    }

    // Strip off the '/Automation' switch from the path
    char *x = strrchr(szPath, '/');
    if(0!= x) // If no /Automation switch on the path
    {
    int result = x - szPath;
    szPath[result]  = '\0';  // If switch there, strip it
    }
    return TRUE;
}

BOOL COfficePathDlg::GetVersion(LPCTSTR szApp, LPSTR szVersion, ULONG cSize)
{
    CHAR  szKey[128], szValueName[128];
    HKEY hKey, hKey1;

    wsprintf(szKey, "%s", szApp);
    LONG lRet = RegOpenKeyEx(HKEY_CLASSES_ROOT, szKey, 0, KEY_ALL_ACCESS, &hKey);
    if (lRet != ERROR_SUCCESS) {
    // Word is registered, but no local server can be found!!!
    AfxMessageBox("Could not get CLSID from ProgID, Make sure ProgID is correct", MB_OK, 0);
        return FALSE;
    }

    wsprintf(szValueName, "%s", "CurVer");
    lRet = RegOpenKeyEx(hKey, szValueName, 0, KEY_ALL_ACCESS, &hKey1);
    if (lRet != ERROR_SUCCESS) {
    // Excel is registered, but no local server can be found!!!
        return FALSE;
    }

    // Get the Version information
    lRet = RegQueryValueEx(hKey1, NULL, NULL, NULL, (BYTE*)szVersion, &cSize);

    // Close the registry keys

    RegCloseKey(hKey1);
    RegCloseKey(hKey);

    // Error while querying for value
    if (lRet != ERROR_SUCCESS)
       return FALSE;

    // At this point szVersion contains the ProgID followed by a number.
    // For example, Word 97 will return Word.Application.8 and Word 2000 will return Word.Application.9


    // Store the version number
    char *x = strrchr(szVersion, '.');
    szVersion[0] = *(x + 1);
    szVersion[1] = '\0';

    if (strcmp(szVersion, "6") == 0)
    strcpy(szVersion, "Version 95");
    else if (strcmp(szVersion, "8") == 0)
        strcpy(szVersion, "Version 97");
        else if  (strcmp(szVersion, "9") == 0)
            strcpy(szVersion, "Version 2000");
            else if (strcmp(szVersion,???? == 0)
            strcpy(szVersion, ?쏺ersion 2002??;

            else
            strcpy(szVersion, "Version unknown");
    return TRUE;

}
12. Build the Project.
When you run the application, type the ProgID for an Office application in the edit box. Note: an example of a ProgID is Word.Application. Click the GetPath button to retrieve the path and click the GetVersion button to retrieve the registered version.

Additional Notes

If you have multiple versions of an Office application installed on your system, the version number corresponds to the application that is registered. In most cases, the registered version is the last version you ran.

If the server application is not installed, the calls to open its associated registry keys fail. You can use error handling in this situation to determine if the server application is installed.
 
 
 
 

댓글

이 블로그의 인기 게시물

80040154 오류로 인해 CLSID가 {xxxx-...}인 구성 요소의 COM 클래스 팩터리를 검색하지 못했습니다.

원문보기 .NET 으로 만든 응용프로그램에서 com 객체를 호출한 경우 Windows7 64bit 에서 제목과 같은 에러가 발생했다. Win32 COM 과 .NET 프로그램간의 호환성 때문에 생긴 문제였다. 원인은 .NET 실행시 JIT 컴파일러에 의해 최적화된 기계어로 변환되기 때문.. Win32 COM은 컴파일시.. Win32 COM에 맞춰 빌드 속성에서 하위버전으로 맞춰 컴파일을 다시하는 방법도 있지만 메인 프로젝트가 .NET이라면 참조되는 모든 프로젝트를 다 바꿔야할 노릇.. 또 다른 방법은 COM+를 이용하여 독립적으로 만드는 것이다. 분리시키는 방법은 아래 주소해서 확인할 수 있다. http://support.microsoft.com/kb/281335 나의 경우는 Win32 COM DLL을 64비트 .NET 프로그램에서 참조하니 COM 객체를 제대로 호출하지 못하였습니다. 그래서 .NET 프로그램의 Target Machine을 x86으로 설정하니 제대로 COM 객체를 호출하였습니다.

[Pyinstaller] 실행 파일 관리자 권한 획득하기

고객사에서 일부 사용자에게서 프로그램 오류가 발생한다며 아래와 같이 에러 캡처를 보내왔습니다. 프로그램에서 로그를 남기기 위해 로그 파일을 생성하는데 권한의 문제로 로그 파일을 생성하지 못해 프로그램 오류가 발생한 것 같습니다. 처음에는 Python 코드에서 관리자 권한을 요청하는 코드를 넣으려고 했는데, 실제로 Stackoverflow를 찾아보면 이런 내용이 나옵니다. 프로그램이 관리자 권한으로 실행되지 않았다면 관리자 권한으로 다시 프로그램을 실행시키는 코드입니다. import os import sys import win32com.shell.shell as shell ASADMIN = 'asadmin' if sys.argv[-1] != ASADMIN: script = os.path.abspath(sys.argv[0]) params = ' '.join([script] + sys.argv[1:] + [ASADMIN]) shell.ShellExecuteEx(lpVerb='runas', lpFile=sys.executable, lpParameters=params) sys.exit(0) 하지만 개인적으로 이런 방식은 마음에 들지 않았고 조금 더 찾아보니 Pyinstaller로 exe 파일을 만들 때 옵션을 설정하여 관리자 권한을 요청하도록 할 수 있다고 합니다. --uac-admin을 옵션에 추가하면 프로그램 실행 시 관리자 권한을 요청할 수 있습니다. pyinstaller.exe --uac-admin sample.py 하지만 안타깝게도 이 방식은 원하는 대로 동작하지 않았습니다. 마지막으로 manifest 파일을 이용하여 시도해보았습니다. spec 파일을 이용하여 pyinstaller로 빌드하면 <실행 파일 이름>.manifest 라는 파일이 생성됩니다. 파일에서 아랫부분을 찾아볼 수 있습니다. <security> <re

초간단 프로그램 락 걸기

프로그램에 락을 걸 일이 생겨났다. 하드웨어 락을 걸면 쉬울텐데 그 정도는 아니고 프로그램의 실행 날짜를 제한 해 달라고 한다. 그래서 파일(license.lic)을 가지고 락을 걸리고 결정을 했다. 요구 사항은 아래와 같다. 1. license.lic 파일이 없으면 프로그램을 실행 할수 없게 한다. 2. 지정한 날짜를 넘어서는 프로그램을 실행 할수 없게 한다. 3. 사용자가 시스템 날짜를 되돌렸을때 인식하여 프로그램을 실행 할수 없게 한다. 음.... 1.번 문제는 사용자가 프로그램을 실행하기 위해서 license.lic 파일을 받아야만 한다. license.lic 파일에는 최근 실행 날짜/종료날짜 이런식으로 적도록 한다.(물론 내용은 암호화 한다.) 최근 실행날짜는 프로그램이 실행때마다 업데이트 하도록 하고 시스템 날짜와 비교하여 시스템 날짜가 최근 실행 날짜보다 이전의 날짜면 시스템 날짜를 되돌렸다고 인식하도록 한다.(3.번 문제 해결) 시스템 날짜와 종료 날짜를 비교하여 시스템 날짜가 종료 날짜를 넘으면 프로그램을 실행 할수 없도록 한다.(2.번 문제 해결)