1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

簡易版 画面を閉じる (SendMessage)

Last updated at Posted at 2024-03-07

WPFでも動くと思います。
FindWindowでタイトル検索してあった場合はSendMessageでWM_CLOSE送るだけ。
サンプルではC: のトップDirを開いているエクスプローラを閉じる。
(複数ある場合はループさせるなり要工夫)

使い道としては、
・面倒な閉じる作業の自動化
・利用者に特定アプリを使用できないようにしたい等。

同様にDllImportでShowWindowを指定してSW_MAXIMIZE送ると最大化したり色々できます。

using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace WindowsFormsApp1 {
    public partial class Form1 : Form {

        // #define WM_CLOSE 0x0010

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll")]
        public static extern int SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);

        public Form1() {
            InitializeComponent();

            IntPtr hWnd = FindWindow(null, "C:\\");
            if (hWnd != IntPtr.Zero) SendMessage(hWnd, 0x0010, (IntPtr)0, (IntPtr)0);
            
        }

        private void Form1_Load(object sender, EventArgs e) {
        }
    }
}

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?