KeiStory

728x90
반응형

C# Edge 에서 지정한 Tab 닫도록 처리하기

 

Edge 에서 지정한 Tab 을 닫고 싶을 때 처리하는 방법입니다.

열려있는 Tab중에 찾고자 하는 Tab 이름이 유일한 경우 처리가 가능합니다.

using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Forms;

namespace WpfApp
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Process[] procsEdge = Process.GetProcessesByName("msedge");
            foreach (Process Edge in procsEdge)
            {
                if (Edge.MainWindowHandle != IntPtr.Zero)
                {
                    AutomationElement root = AutomationElement.FromHandle(Edge.MainWindowHandle);

                    var tabs = root.FindAll(TreeScope.Descendants, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.TabItem));

                    foreach (AutomationElement tabitem in tabs)
                    {
                        if (tabitem.Current.Name.ToUpper().Contains("GOOGLE"))
                        {
                            tabitem.SetFocus();
                            SendKeys.SendWait("^{w}");
                        }
                    }
                }
            }
        }
    }
}

위 코드를 보면 알수 있지만 특정('GOOGLE')탭을 찾아 Focus 를 가게합니다.

그런 후 탭을 닫는 단축키를 실행하여 처리가 됩니다.

WPF .NET6 이상인 프로젝트인 경우 프로젝트 파일에 아래항목이 추가되어야 SendKeys 를 사용할 수 있습니다.
<UseWindowsForms>true</UseWindowsForms>

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetFramework>net6.0-windows</TargetFramework>
    <Nullable>enable</Nullable>
    <UseWPF>true</UseWPF>
    <UseWindowsForms>true</UseWindowsForms>
  </PropertyGroup>

</Project>

 

결과

탭 닫기 전

탭 닫은 후

728x90

공유하기

facebook twitter kakaoTalk kakaostory naver band