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
정성태

[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13605정성태4/23/2024200닷넷: 2246. C# - Python.NET을 이용한 파이썬 소스코드 연동파일 다운로드1
13604정성태4/22/2024221오류 유형: 901. Visual Studio - Unable to set the next statement. Set next statement cannot be used in '[Exception]' call stack frames.
13603정성태4/21/2024294닷넷: 2245. C# - IronPython을 이용한 파이썬 소스코드 연동파일 다운로드1
13602정성태4/20/2024645닷넷: 2244. C# - PCM 오디오 데이터를 연속(Streaming) 재생 (Windows Multimedia)파일 다운로드1
13601정성태4/19/2024746닷넷: 2243. C# - PCM 사운드 재생(NAudio)파일 다운로드1
13600정성태4/18/2024754닷넷: 2242. C# - 관리 스레드와 비관리 스레드
13599정성태4/17/2024800닷넷: 2241. C# - WAV 파일의 PCM 사운드 재생(Windows Multimedia)파일 다운로드1
13598정성태4/16/2024826닷넷: 2240. C# - WAV 파일 포맷 + LIST 헤더파일 다운로드2
13597정성태4/15/2024800닷넷: 2239. C# - WAV 파일의 PCM 데이터 생성 및 출력파일 다운로드1
13596정성태4/14/20241036닷넷: 2238. C# - WAV 기본 파일 포맷파일 다운로드1
13595정성태4/13/20241047닷넷: 2237. C# - Audio 장치 열기 (Windows Multimedia, NAudio)파일 다운로드1
13594정성태4/12/20241064닷넷: 2236. C# - Audio 장치 열람 (Windows Multimedia, NAudio)파일 다운로드1
13593정성태4/8/20241074닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
13592정성태4/2/20241215C/C++: 165. CLion으로 만든 Rust Win32 DLL을 C#과 연동
13591정성태4/2/20241187닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
13590정성태3/31/20241078Linux: 70. Python - uwsgi 응용 프로그램이 k8s 환경에서 OOM 발생하는 문제
13589정성태3/29/20241150닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
13588정성태3/28/20241246닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신 [2]파일 다운로드1
13587정성태3/27/20241168오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
13586정성태3/27/20241320Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
13585정성태3/26/20241104Windows: 262. PerformanceCounter의 InstanceName에 pid를 추가한 "Process V2"
13584정성태3/26/20241058개발 환경 구성: 708. Unity3D - C# Windows Forms / WPF Application에 통합하는 방법파일 다운로드1
13583정성태3/25/20241175Windows: 261. CPU Utilization이 100% 넘는 경우를 성능 카운터로 확인하는 방법
13582정성태3/19/20241433Windows: 260. CPU 사용률을 나타내는 2가지 수치 - 사용량(Usage)과 활용률(Utilization)파일 다운로드1
13581정성태3/18/20241606개발 환경 구성: 707. 빌드한 Unity3D 프로그램을 C++ Windows Application에 통합하는 방법
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...