> 백엔드 개발 > C++ > Windows에서 파일 형식을 열기 위한 기본 응용 프로그램을 프로그래밍 방식으로 결정하는 방법은 무엇입니까?

Windows에서 파일 형식을 열기 위한 기본 응용 프로그램을 프로그래밍 방식으로 결정하는 방법은 무엇입니까?

Susan Sarandon
풀어 주다: 2025-01-05 01:26:40
원래의
740명이 탐색했습니다.

How to Programmatically Determine the Default Application for Opening a File Type in Windows?

Windows에서 파일 형식을 열기 위한 기본 응용 프로그램 결정

적절한 기본 응용 프로그램으로 파일을 여는 것은 많은 응용 프로그램에서 일반적인 작업입니다. C#을 사용하여 .NET Framework 2.0에서 이를 달성하려면 System.Diagnostics.Process.Start 메서드를 활용할 수 있습니다. 그러나 이 방법을 사용하려면 기본 애플리케이션을 결정하기 위해 정확한 파일 확장자가 필요합니다.

원하는 기본 애플리케이션에서 특정 확장자가 없는 파일을 열려면 파일 형식과 연결된 애플리케이션을 검색해야 합니다. 레지스트리를 사용하여 이 연결을 확인하는 것은 신뢰할 수 없는 접근 방식이지만 Win32 API는 보다 강력한 방법을 제공합니다.

Shlwapi.dll 라이브러리의 AssocQueryString 함수를 사용하면 특정 파일 형식에 대한 연결을 쿼리할 수 있습니다. 이 함수를 사용하면 파일 형식에 대한 기본 명령, 실행 파일 또는 기타 관련 정보를 확인할 수 있습니다.

샘플 사용법은 AssocQueryString을 활용하여 파일 확장자와 관련된 명령을 얻는 방법을 보여줍니다.

using System;
using System.Runtime.InteropServices;

namespace FileAssociation
{
    class Program
    {
        [DllImport("Shlwapi.dll", CharSet = CharSet.Unicode)]
        public static extern uint AssocQueryString(
            AssocF flags, AssocStr str, string pszAssoc, string pszExtra, 
            [Out] StringBuilder pszOut, ref uint pcchOut);

        public enum AssocF
        {
            None = 0x00000000,
            Init_NoRemapCLSID = 0x00000001,
            Init_ByExeName = 0x00000002,
            Open_ByExeName = 0x00000002,
            Init_DefaultToStar = 0x00000004,
            Init_DefaultToFolder = 0x00000008,
            NoUserSettings = 0x00000010,
            NoTruncate = 0x00000020,
            Verify = 0x00000040,
            RemapRunDll = 0x00000080,
            NoFixUps = 0x00000100,
            IgnoreBaseClass = 0x00000200,
            Init_IgnoreUnknown = 0x00000400,
            Init_Fixed_ProgId = 0x00000800,
            Is_Protocol = 0x00001000,
            Init_For_File = 0x00002000
        }

        public enum AssocStr
        {
            Command = 1,
            Executable,
            FriendlyDocName,
            FriendlyAppName,
            NoOpen,
            ShellNewValue,
            DDECommand,
            DDEIfExec,
            DDEApplication,
            DDETopic,
            InfoTip,
            QuickTip,
            TileInfo,
            ContentType,
            DefaultIcon,
            ShellExtension,
            DropTarget,
            DelegateExecute,
            Supported_Uri_Protocols,
            ProgID,
            AppID,
            AppPublisher,
            AppIconReference,
            Max
        }

        public static string AssocQueryString(AssocStr association, string extension)
        {
            const int S_OK = 0x00000000;
            const int S_FALSE = 0x00000001;

            uint length = 0;
            uint ret = AssocQueryString(AssocF.None, association, extension, null, null, ref length);
            if (ret != S_FALSE)
            {
                throw new InvalidOperationException("Could not determine associated string");
            }

            var sb = new StringBuilder((int)length); // (length - 1) will probably work too as the marshaller adds null termination
            ret = AssocQueryString(AssocF.None, association, extension, null, sb, ref length);
            if (ret != S_OK)
            {
                throw new InvalidOperationException("Could not determine associated string");
            }

            return sb.ToString();
        }

        public static void Main(string[] args)
        {
            string extension = ".txt";
            string command = AssocQueryString(AssocStr.Command, extension);
            System.Diagnostics.Process.Start(command, "test.txt");
        }
    }
}
로그인 후 복사

위 내용은 Windows에서 파일 형식을 열기 위한 기본 응용 프로그램을 프로그래밍 방식으로 결정하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿