Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

(시리즈 글이 3개 있습니다.)
.NET Framework: 584. C# - 파일 확장자에 연결된 프로그램을 등록하는 방법 (1) - 기본
; https://www.sysnet.pe.kr/2/0/10966

.NET Framework: 585. C# - 파일 확장자에 연결된 프로그램을 등록하는 방법 (2) - 웹 브라우저가 다운로드 후 자동 실행
; https://www.sysnet.pe.kr/2/0/10967

.NET Framework: 586. C# - 파일 확장자에 연결된 프로그램을 등록하는 방법 (3) - "Open with" 목록에 등록
; https://www.sysnet.pe.kr/2/0/10969




C# - 파일 확장자에 연결된 프로그램을 등록하는 방법 (3) - "Open with" 목록에 등록

지난번에 .1myext 확장자에 연결 프로그램을 등록했는데요.

C# - 파일 확장자에 연결된 프로그램을 등록하는 방법 (1) - 기본
; https://www.sysnet.pe.kr/2/0/10966

C# - 파일 확장자에 연결된 프로그램을 등록하는 방법 (2) - 웹 브라우저가 다운로드 후 자동 실행
; https://www.sysnet.pe.kr/2/0/10967

그런데, 사용자가 탐색기에서 특정 파일과 연결하고 싶어 마우스 우클릭 후 "Open with" / "Choose another app"을 선택해도 우리가 만든 예제 프로그램은 항목에 나오질 않습니다.

그 목록에 끼고 싶다면, "SOFTWARE\Classes\Applications" 경로에 command를 소유한 레지스트리 키를 하나 등록해 두어야 합니다.

Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\SOFTWARE\Classes\Applications]

[HKEY_CURRENT_USER\SOFTWARE\Classes\Applications\YourExt.exe]

[HKEY_CURRENT_USER\SOFTWARE\Classes\Applications\YourExt.exe\shell]

[HKEY_CURRENT_USER\SOFTWARE\Classes\Applications\YourExt.exe\shell\open]

[HKEY_CURRENT_USER\SOFTWARE\Classes\Applications\YourExt.exe\shell\open\command]
@="\"C:\\YourExt\\bin\\Debug\\YourExt.exe\" \"%1\""

코드로 표현하면 대략 다음과 같은 정도의 변화만 있으면 됩니다.

private static void ProcessFileExtReg(bool register)
{
    using (RegistryKey classesKey = Registry.CurrentUser.OpenSubKey(@"Software\Classes", true))
    {
        // ...[생략]...

        RegistApplication(classesKey, register);
    }
}

private static void RegistApplication(RegistryKey classesKey, bool register)
{
    using (RegistryKey appKey = classesKey.OpenSubKey("Applications", true))
    {
        if (register == true)
        {
            using (RegistryKey exeKey = appKey.CreateSubKey(assocExeFileName))
            {
                RegistShellOpenCommand(exeKey);
            }
        }
        else
        {
            // ...[생략]...
        }
    }
}

private static void RegistShellOpenCommand(RegistryKey baseKey)
{
    using (RegistryKey shellKey = baseKey.CreateSubKey("shell"))
    {
        using (RegistryKey openKey = shellKey.CreateSubKey("open"))
        {
            using (RegistryKey commandKey = openKey.CreateSubKey("command"))
            {
                string assocExePath = GetProcessPath();
                string assocCommand = string.Format("\"{0}\" \"%1\"", assocExePath);

                commandKey.SetValue(null, assocCommand);
            }
        }
    }
}

변경된 등록 프로그램을 실행한 후, 탐색기에서 아무 파일이나 우클릭을 해 "Open with" / "Choose another app" 메뉴를 선택하면 다음과 같이 프로그램 항목이 보이는 것을 확인할 수 있습니다.

yourext_openwith_1.png

그런데, 이렇게 사용자가 "Open with"로 연결 프로그램을 바꾸면 어떤 변화가 있을까요?

아마도, 가장 쉬운 방법으로 그냥 해당 확장자의 연결 항목을 바꿔버리는 걸로 구현하는 것을 생각해 볼 수 있습니다. 즉, 다음과 같이 연결된 프로그램이 등록되었다면,

Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\Software\Classes\yourext.1myext.v1\shell\open\command]
@="c:\path\to\yourext.exe \"%1\""

[HKEY_CURRENT_USER\Software\Classes\.1myext]
@="yourext.1myext.v1"

이를 notepad.exe로 바꾼다면 다음과 같이 변경하면 그만입니다.

Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\Software\Classes\.1myext]
@="txtfile"

그런데, 마이크로소프트의 '탐색기' 개발자는 이런 방식을 취하지 않았습니다. 실제로, "test.1myext" 파일을 "Open with" 기능으로 연결 프로그램을 메모장으로 바꾸면 다음의 레지스트리 키가 생성되고,

HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.1myext

그 하위에 "OpenWithList" 키를 통해 해당 확장자로 연결된 적이 있는 프로그램들의 "SOFTWARE\Classes\Applications\[...exe...]" 식별자가 등록됩니다. 가령, 방금 전에 ".1myext" 확장자를 "Open with"로 메모장과 연결했다면 다음과 같은 설정을 볼 수 있습니다.

yourext_openwith_2.png

OpenWithList가 연결된 적이 있는 프로그램들의 목록을 보여준다면, 실제로 현재 사용자가 연결한 프로그램 설정은 "UserChoice"에 있습니다.

yourext_openwith_3.png

"ProgId" 값이 "Applications\NOTEPAD.EXE"로 나오는데, 이는 "SOFTWARE\Classes\Applications\NOTEPAD.EXE" 항목을 의미합니다. 여기서 재미있는 것은 "Hash" 값입니다. 현재 "Dx/cvUgkjM8="로 되어 있는데 이는 "ProgId"의 유효성 검사에서 오는 듯 합니다. 즉, 외부에서 프로그래밍적인 방법을 이용해 임의로 이 값을 바꾸는 것이 허용되지 않습니다. 가령 제가 "ProgId" 값을 "Applications\test.exe"로 바꾸고 싶어도 Hash 값 생성 규칙을 알 수 없기 때문에 유효하지 않게 되는 것입니다. (참고로, 같은 NOTEPAD.EXE로 등록해도 다시 하면 Hash값이 바뀝니다.)

또 한가지 재미있는 점은, 연결 프로그램의 설정 값에 대한 우선 순위가 "Software\Classes\.1myext"보다 "SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.1myext"의 것이 더 높다는 점입니다. 이 때문에 사용자가 설정한 값이 이후 설치되는 프로그램의 확장자 연결에 상관없이 독립적으로 유지가 가능합니다. 사용자 입장에서의 배려가 돋보이는 부분입니다.




그렇다면, 자신의 프로그램으로 특정 확장자 연결을 강제로 설정하고 싶다면 어떻게 해야 할까요? 공식적인 방법은 없는 듯 하지만, 어쨌든 레지스트리 등록 정보를 기반으로 밀어버리는 것을 해볼 수 있습니다. 제 경우에 다음과 같은 레지스트리 값을 모두 새로운 프로그램으로 연결해 보았는데요.

HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\FileExts\UserChoice 삭제
HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\Roaming\OpenWith\FileExts\.1myext 삭제
HKEY_CURRENT_USER\Software\Classes\.1myext 의 ProgId 교체

위의 역할을 하는 프로그램을 첨부 파일의 ReplaceAssoc 프로젝트로 구현했습니다. 가령, ".1myext" 확장자를 교체하고 싶다면 다음과 같이 실행해 주면 됩니다.

c:\temp>ReplaceAssoc .1myext

테스트 해보면 windows 8에서는 ".1myext" 확장자 교체는 잘 되었지만 알집과 연결된 ".zip"의 경우에는 뭔가 설정이 더 있어서 그런지 연결 프로그램이 해제된 상태로만 바뀌고 교체까지는 안되었습니다. 반면, 윈도우 10의 경우 모두 연결 프로그램이 잘 교체되었습니다. (물론, 비공식적인 방법이므로 향후 얼마든지 동작은 바뀔 수 있습니다.)

(첨부 파일은 이 글의 예제 코드를 포함합니다.)





[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 7/10/2021]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 46  47  48  49  50  51  52  53  54  55  56  [57]  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12201정성태3/18/202010836오류 유형: 611. git-credential-manager.exe: Using credentials for username "Personal Access Token". [1]
12200정성태3/18/202011289VS.NET IDE: 145. NuGet + Github 라이브러리 디버깅 관련 옵션 3가지 - "Enable Just My Code" / "Enable Source Link support" / "Suppress JIT optimization on module load (Managed only)"
12199정성태3/17/20209145오류 유형: 610. C# - CodeDomProvider 사용 시 Unhandled Exception: System.IO.DirectoryNotFoundException: Could not find a part of the path '...\f2_6uod0.tmp'.
12198정성태3/17/202011855오류 유형: 609. SQL 서버 접속 시 "Cannot open user default database. Login failed."
12197정성태3/17/202011002VS.NET IDE: 144. .NET Core 콘솔 응용 프로그램을 배포(publish) 시 docker image 자동 생성 - 두 번째 이야기 [1]
12196정성태3/17/20208922오류 유형: 608. The ServicedComponent being invoked is not correctly configured (Use regsvcs to re-register).
12195정성태3/16/202010656.NET Framework: 902. C# - 프로세스의 모든 핸들을 열람 - 세 번째 이야기
12194정성태3/16/202012986오류 유형: 607. PostgreSQL - Npgsql.NpgsqlException: sorry, too many clients already
12193정성태3/16/20209602개발 환경 구성: 485. docker - SAP Adaptive Server Enterprise 컨테이너 실행 [1]
12192정성태3/14/202012070개발 환경 구성: 484. docker - Sybase Anywhere 16 컨테이너 실행
12191정성태3/14/202012435개발 환경 구성: 483. docker - OracleXE 컨테이너 실행 [1]
12190정성태3/14/20208597오류 유형: 606. Docker Desktop 업그레이드 시 "The process cannot access the file 'C:\Program Files\Docker\Docker\resources\dockerd.exe' because it is being used by another process."
12189정성태3/13/202013442개발 환경 구성: 482. Facebook OAuth 처리 시 상태 정보 전달 방법과 "유효한 OAuth 리디렉션 URI" 설정 규칙
12188정성태3/13/202015644Windows: 169. 부팅 시점에 실행되는 chkdsk 결과를 확인하는 방법
12187정성태3/12/20208394오류 유형: 605. NtpClient was unable to set a manual peer to use as a time source because of duplicate error on '...'.
12186정성태3/12/20209470오류 유형: 604. The SysVol Permissions for one or more GPOs on this domain controller and not in sync with the permissions for the GPOs on the Baseline domain controller.
12185정성태3/11/202010129오류 유형: 603. The browser service was unable to retrieve a list of servers from the browser master...
12184정성태3/11/202011585오류 유형: 602. Automatic certificate enrollment for local system failed (0x800706ba) The RPC server is unavailable. [3]
12183정성태3/11/20209938오류 유형: 601. Warning: DsGetDcName returned information for \\[...], when we were trying to reach [...].
12182정성태3/11/202011143.NET Framework: 901. C# Windows Forms - Vista/7 이후의 Progress Bar 업데이트가 느린 문제파일 다운로드1
12181정성태3/11/202011955기타: 76. 재현 가능한 최소한의 예제 프로젝트란? - 두 번째 예제파일 다운로드1
12180정성태3/10/20208567오류 유형: 600. "Docker Desktop for Windows" - EXPOSE 포트가 LISTENING 되지 않는 문제
12179정성태3/10/202019962개발 환경 구성: 481. docker - PostgreSQL 컨테이너 실행
12178정성태3/10/202011451개발 환경 구성: 480. Linux 운영체제의 docker를 위한 tcp 바인딩 추가 [1]
12177정성태3/9/202011112개발 환경 구성: 479. docker - MySQL 컨테이너 실행
12176정성태3/9/202010528개발 환경 구성: 478. 파일의 (sha256 등의) 해시 값(checksum) 확인하는 방법
... 46  47  48  49  50  51  52  53  54  55  56  [57]  58  59  60  ...