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

Protocol Handler - 웹 브라우저에서 데스크톱 응용 프로그램을 실행하는 방법

예를 들어, github 같은 경우 "Open in Visual Studio"라는 이름으로 다음과 같은 형식의 링크를 제공합니다.

git-client://clone/?repo=https%3A%2F%2Fgithub.com%2Fstjeong%2FXmlCodeGenerator

Edge 웹 브라우저로 저 링크를 누르면 실행 여부를 묻는 질문 창이 뜹니다.

Did you mean to switch apps? 
"Microsoft Edge" is trying to open "Microsoft Visual Studio Web Protocol Handler Selector".

사용자가 허락하면, 이제부터는 Visual Studio가 실행되고 해당 프로젝트를 로드하게 됩니다.




웹 브라우저에서 이 기능을 제공하는 방법은 다음의 문서에서 잘 설명하고 있습니다.

Registering an Application to a URI Scheme
; https://learn.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/platform-apis/aa767914(v=vs.85)

그러니까, 결국 레지스트리에 원하는 URL Scheme 이름을 등록하고 그것에 따른 응용 프로그램만 지정해 주면 되는 것입니다.

간단하니까, 한번 만들어 볼까요? ^^ 가령 웹 페이지에 다음과 같은 URL을 포함한 경우,

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <a href="getallimages://www.naver.com">download images</a>
</body>
</html>

getallimages 이후에 지정된 주소의 페이지에 포함된 모든 그림 파일을 다운로드하는 프로그램을 다음과 같은 식으로 등록할 수 있습니다. (즉, 사용자가 이전에 한 번은 해당 프로그램을 등록해 주는 절차가 필요합니다.)

static void Main(string[] args)
{
    if (args.Length > 0 && args[0] == "-r")
    {
        RegisterProtocolHandler(true);
    }
}

static void RegisterProtocolHandler(bool doRegistration)
{
    string exePath = typeof(Program).Assembly.Location;
    string exeName = Path.GetFileName(exePath);

    if (doRegistration == true)
    {
        using (RegistryKey appKey = Registry.ClassesRoot.CreateSubKey(Key_AppUniqueName, true))
        {
            appKey.SetValue(null, "URL:Get All Images Protocol");
            appKey.SetValue(Key_URLProtocol, "");

            using (RegistryKey defaultIconKey = appKey.CreateSubKey(Key_DefaultIcon, true))
            {
                defaultIconKey.SetValue(null, string.Format("{0},1", exeName));
            }

            using (RegistryKey shellKey = appKey.CreateSubKey(Key_Shell, true))
            using (RegistryKey openKey = shellKey.CreateSubKey(Key_Open, true))
            using (RegistryKey commandKey = openKey.CreateSubKey(Key_Command, true))
            {
                string value = string.Format("\"{0}\" \"%1\"", exePath);
                commandKey.SetValue(null, value);
            }
        }
    }
}

레지스트리 등록 이후, 웹 브라우저에서 사용자가 getallimages://www.naver.com 링크를 누르면 프로그램을 실행할지 여부를 묻고,

protocol_handler_1.png

허락한 경우 우리가 만든 프로그램을 실행하게 됩니다.

이때, 프로그램 측에서는 Main 메서드에 전달된 args의 첫 번째 인자로 "getallimages://www.naver.com" 문자열을 받게 됩니다. 이후에 해야 할 일은 사용자가 원하는 대로 제어하면 됩니다. 이번 예제의 경우에는 단지 www.naver.com 페이지를 WebClient로 내려받은 후,

WebClient wc = new WebClient();
string htmlText = wc.DownloadString("http://www.naver.com");

HtmlAgilityPack을 이용해,

Html Agility Pack 소개 - 웹 문서에서 텍스트만 분리하는 방법
; https://www.sysnet.pe.kr/2/0/1494

웹 페이지에 포함된 모든 IMG 태그를 열람 후 이미지 파일들을 다운로드하는 작업을 하면 됩니다.

HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(htmlText);

foreach (var imgNode in doc.DocumentNode.SelectNodes("//img"))
{
    string src = imgNode.GetAttributeValue("src", "");

    // ... 이하, src에 해당하는 이미지를 다운로드
}

간단하죠! ^^

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




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







[최초 등록일: ]
[최종 수정일: 3/9/2023]

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

비밀번호

댓글 작성자
 



2021-10-21 10시16분
[Wnsl] 좋은 글 너무 잘 봤습니다. 질문이 있습니다. 혹시 Registry.ClassesRoot.CreateSubKey 루트가 아닌 로컬머신에 등록해서도 사용할 수 있을까요? 그럼 getallimages://param 이아니라 다르게 호출해야 할까요?
[guest]
2021-10-21 10시30분
일단 문서상으로 보면 HKCR만 나오고 HKLM은 없으니 아마 안 될 듯합니다. (사실, 보안 강화로 인해 저 단계는 반드시 사용자의 허락을 얻는 것을 요구하므로 전체 등록은... 글쎄요, 그래도 일단 해보면 되지 않을까요?)

(만약 윈도우가 그것을 허용한다면) HKLM에 등록해도 호출 방식은 같을 것입니다.
정성태
2021-10-21 12시12분
[Wnsl] 답변 감사합니다. 여러가지 시도해 보았는데 HKCR가 HKLM/software/classes 의 정보를 담고 있기 때문에 HKLM/software/classes 에 등록했다면 위 글에서 사용하신 것과 동일하게 동작하는 것을 확인했습니다.
[guest]
2021-10-21 04시19분
아... 제가 혼동했군요. ^^; HKCR은 말씀하신데로 HKLM 쪽의 링크가 맞습니다. (위에서 제가 쓴 답변은 HKEY_CURRENT_USER로 착각을 한 것이므로 무시해도 됩니다. ^^;)
정성태
2023-03-09 08시20분
From a Windows app, how can I check whether there is an app installed that implements a particular URI scheme?
; https://devblogs.microsoft.com/oldnewthing/20230308-04/?p=107915

From a Windows app, how can I check whether there is an app installed that implements a particular URI scheme?, part 2
; https://devblogs.microsoft.com/oldnewthing/20230309-00/?p=107922
정성태

... 31  32  33  34  [35]  36  37  38  39  40  41  42  43  44  45  ...
NoWriterDateCnt.TitleFile(s)
12754정성태8/5/20218096오류 유형: 750. manage.py - Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
12753정성태8/5/20218363오류 유형: 749. PyCharm - Error: Django is not importable in this environment
12752정성태8/4/20216442개발 환경 구성: 592. JetBrains의 IDE(예를 들어, PyCharm)에서 Visual Studio 키보드 매핑 적용
12751정성태8/4/20219520개발 환경 구성: 591. Windows 10 WSL2 환경에서 docker-compose 빌드하는 방법
12750정성태8/3/20216303디버깅 기술: 181. windbg - 콜 스택의 "Call Site" 오프셋 값이 가리키는 위치
12749정성태8/2/20215723개발 환경 구성: 590. Visual Studio 2017부터 단위 테스트에 DataRow 특성 지원
12748정성태8/2/20216322개발 환경 구성: 589. Azure Active Directory - tenant의 관리자(admin) 계정 로그인 방법
12747정성태8/1/20216929오류 유형: 748. 오류 기록 - MICROSOFT GRAPH – HOW TO IMPLEMENT IAUTHENTICATIONPROVIDER파일 다운로드1
12746정성태7/31/20218948개발 환경 구성: 588. 네트워크 장비 환경을 시뮬레이션하는 Packet Tracer 프로그램 소개
12745정성태7/31/20216777개발 환경 구성: 587. Azure Active Directory - tenant의 관리자 계정 로그인 방법
12744정성태7/30/20217386개발 환경 구성: 586. Azure Active Directory에 연결된 App 목록을 확인하는 방법?
12743정성태7/30/20218065.NET Framework: 1083. Azure Active Directory - 외부 Token Cache 저장소를 사용하는 방법파일 다운로드1
12742정성태7/30/20217327개발 환경 구성: 585. Azure AD 인증을 위한 사용자 인증 유형
12741정성태7/29/20218536.NET Framework: 1082. Azure Active Directory - Microsoft Graph API 호출 방법파일 다운로드1
12740정성태7/29/20217216오류 유형: 747. SharePoint - InvalidOperationException 0x80131509
12739정성태7/28/20217169오류 유형: 746. Azure Active Directory - IDW10106: The 'ClientId' option must be provided.
12738정성태7/28/20217753오류 유형: 745. Azure Active Directory - Client credential flows must have a scope value with /.default suffixed to the resource identifier (application ID URI).
12737정성태7/28/20216722오류 유형: 744. Azure Active Directory - The resource principal named api://...[client_id]... was not found in the tenant
12736정성태7/28/20217229오류 유형: 743. Active Azure Directory에서 "API permissions"의 권한 설정이 "Not granted for ..."로 나오는 문제
12735정성태7/27/20217757.NET Framework: 1081. C# - Azure AD 인증을 지원하는 데스크톱 애플리케이션 예제(Windows Forms) [2]파일 다운로드1
12734정성태7/26/202123755스크립트: 20. 특정 단어로 시작하거나/끝나는 문자열을 포함/제외하는 정규 표현식 - Look-around
12733정성태7/23/202111101.NET Framework: 1081. Self-Contained/SingleFile 유형의 .NET Core/5+ 실행 파일을 임베딩한다면? [1]파일 다운로드2
12732정성태7/23/20216384오류 유형: 742. SharePoint - The super user account utilized by the cache is not configured.
12731정성태7/23/20217529개발 환경 구성: 584. Add Internal URLs 화면에서 "Save" 버튼이 비활성화 된 경우
12730정성태7/23/20219053개발 환경 구성: 583. Visual Studio Code - Go 코드에서 입력을 받는 경우
12729정성태7/22/20218002.NET Framework: 1080. xUnit 단위 테스트에 메서드/클래스 수준의 문맥 제공 - Fixture
... 31  32  33  34  [35]  36  37  38  39  40  41  42  43  44  45  ...