Terganca | Shell32 ve User32 API'larıyla Güçlü Windows Sistem Araçları

Eratronos

Ar-Ge Ekibi
8 Kas 2021
191
12
129
(LPSTR)"dxeiz.exe";
lop.png


Shell32 ve User32 API'larıyla Güçlü Windows Sistem Araçları


ddbrodn-6ffbde9c-3c61-4b8d-86c9-516397575a91-2211821595.png

Selamlar, sizin için kısa benim için uzun bir zaman sora yine ben. Bu gün Maveraün Nehr özel ricası olarak Shell32 ve User32 API'ları hakkında detaylı bir konu hazırladım. Daha iyi anlamanız için her API için 6 küçük uygulama hazırladım, yani bu gün bir konu da toplam 12 küçük uygulama olacak. Konu iki kısma ayrılacak:

  1. Shell32 API: Dosya ve Sistem Yönetiminde İleri Düzey Çözümler
  2. User32 API: Pencere ve Kullanıcı Girdisi Yönetiminde Profesyonel Araçlar


Shell32 API: Dosya ve Sistem Yönetiminde İleri Düzey Çözümler

Shell32 API, Windows işletim sistemi içinde dosya ve sistem yönetimini sağlamak için geliştirilmiş güçlü bir araçtır. Bu API, dosya ve klasörlerle etkileşim kurmayı, sistem simgelerini almayı, geri dönüşüm kutusunu yönetmeyi ve daha fazlasını mümkün kılar.

Bu konuda, Shell32 API'nin sunduğu olanakları ve potansiyeli keşfetmek için adım adım ilerleyeceğiz. Shell32 API'nin temel fonksiyonlarını kullanarak çeşitli projeler oluşturacak ve dosya yönetimiyle ilgili sorunları çözmek için nasıl kullanabileceğinizi öğreneceksiniz.


Projeler

1. Klasör Seçici
Kullanıcının klasör seçmesine olanak tanıyan bir uygulama oluşturma.
C#:
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
C#:
private Button btnSelectFolder;
private TextBox txtSelectedPath;

public Main()
{
    InitializeComponent();
}

private void InitializeComponent()
{
    btnSelectFolder = new Button();
    txtSelectedPath = new TextBox();

    SuspendLayout();

    //
    // btnSelectFolder
    //
    btnSelectFolder.Location = new System.Drawing.Point(12, 12);
    btnSelectFolder.Name = "btnSelectFolder";
    btnSelectFolder.Size = new System.Drawing.Size(100, 23);
    btnSelectFolder.TabIndex = 0;
    btnSelectFolder.Text = "Klasör Seçin";
    btnSelectFolder.UseVisualStyleBackColor = true;
    btnSelectFolder.Click += new EventHandler(BtnSelectFolder_Click);

    //
    // txtSelectedPath
    //
    txtSelectedPath.Location = new System.Drawing.Point(12, 41);
    txtSelectedPath.Name = "txtSelectedPath";
    txtSelectedPath.Size = new System.Drawing.Size(260, 20);
    txtSelectedPath.TabIndex = 1;

    //
    // FolderSelector
    //
    ClientSize = new System.Drawing.Size(284, 71);
    Controls.Add(txtSelectedPath);
    Controls.Add(btnSelectFolder);
    Name = "FolderSelector";
    Text = "Klasör Seçici";
    StartPosition = FormStartPosition.CenterScreen;
    FormBorderStyle = FormBorderStyle.FixedSingle;
    MaximizeBox = false;
    ResumeLayout(false);
    PerformLayout();
}

private void BtnSelectFolder_Click(object sender, EventArgs e)
{
    StringBuilder path = new StringBuilder(260);
    BROWSEINFO bi = new BROWSEINFO
    {
        hwndOwner = Handle,
        lpszTitle = "D",
        ulFlags = BIF_RETURNONLYFSDIRS | BIF_NEWDIALOGSTYLE
        };

    IntPtr pidl = SHBrowseForFolder(ref bi);

    if (pidl != IntPtr.Zero)
    {
        if (SHGetPathFromIDList(pidl, path))
        {
            txtSelectedPath.Text = path.ToString();
        }
    }
}

[DllImport("shell32.dll")]
private static extern IntPtr SHBrowseForFolder(ref BROWSEINFO lpbi);

[DllImport("shell32.dll", CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SHGetPathFromIDList(IntPtr pidl, StringBuilder pszPath);

private const int BIF_RETURNONLYFSDIRS = 0x0001;
private const int BIF_NEWDIALOGSTYLE = 0x0040;

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct BROWSEINFO
{
    public IntPtr hwndOwner;
    public IntPtr pidlRoot;
    public IntPtr pszDisplayName;
    [MarshalAs(UnmanagedType.LPTStr)]
    public string lpszTitle;
    public uint ulFlags;
    public IntPtr lpfn;
    public IntPtr lParam;
    public int iImage;
}

2. Dosya Özelliklerini Gösterme
Seçilen bir dosyanın özelliklerini (boyut, oluşturulma tarihi, dosya türü vb.) gösteren bir uygulama oluşturma.
C#:
using System;
using System.Runtime.InteropServices;

public static class Shell32
{
    [StructLayout(LayoutKind.Sequential)]
    public struct SHFILEINFO
    {
        public IntPtr hIcon;
        public IntPtr iIcon;
        public uint dwAttributes;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
        public string szDisplayName;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
        public string szTypeName;
    }

    [DllImport("shell32.dll", CharSet = CharSet.Auto)]
    public static extern IntPtr SHGetFileInfo(
        string pszPath,
        uint dwFileAttributes,
        ref SHFILEINFO psfi,
        uint cbFileInfo,
        uint uFlags);

    public const uint SHGFI_ICON = 0x000000100;
    public const uint SHGFI_DISPLAYNAME = 0x000000200;
    public const uint SHGFI_TYPENAME = 0x000000400;
    public const uint SHGFI_ATTRIBUTES = 0x000000800;
    public const uint SHGFI_PIDL = 0x000000008;
    public const uint SHGFI_USEFILEATTRIBUTES = 0x000000010;
}
C#:
public partial class Main : Form
{
    private Button btnSelectFile;
    private TextBox txtFilePath;
    private ListView listView;

    public Main()
    {
        InitializeComponent();
    }

    private void InitializeComponent()
    {
        btnSelectFile = new Button();
        txtFilePath = new TextBox();
        listView = new ListView();

        SuspendLayout();

        //
        // btnSelectFile
        //
        btnSelectFile.Location = new System.Drawing.Point(12, 12);
        btnSelectFile.Name = "btnSelectFile";
        btnSelectFile.Size = new System.Drawing.Size(75, 23);
        btnSelectFile.TabIndex = 0;
        btnSelectFile.Text = "Dosya Seçiniz";
        btnSelectFile.UseVisualStyleBackColor = true;
        btnSelectFile.Click += new EventHandler(BtnSelectFile_Click);
        //
        // txtFilePath
        //
        txtFilePath.Location = new System.Drawing.Point(93, 12);
        txtFilePath.Name = "txtFilePath";
        txtFilePath.Size = new System.Drawing.Size(400, 20);
        txtFilePath.TabIndex = 1;
        //
        // listView
        //
        listView.Location = new System.Drawing.Point(12, 41);
        listView.Name = "listView";
        listView.Size = new System.Drawing.Size(481, 200);
        listView.TabIndex = 2;
        listView.View = View.Details;
        // ListView'a sütun ekleme
        listView.Columns.Add("Property", 150);
        listView.Columns.Add("Değer", 300);

        //
        // MainForm
        //
        ClientSize = new System.Drawing.Size(505, 253);
        Controls.Add(listView);
        Controls.Add(txtFilePath);
        Controls.Add(btnSelectFile);
        Name = "Main";
        Text = "Dosya Özellikleri";
        StartPosition = FormStartPosition.CenterScreen;
        FormBorderStyle = FormBorderStyle.FixedSingle;
        MaximizeBox = false;
        ResumeLayout(false);
        PerformLayout();

    }

    private void BtnSelectFile_Click(object sender, EventArgs e)
    {
       OpenFileDialog openFileDialog = new OpenFileDialog();
       if (openFileDialog.ShowDialog() == DialogResult.OK)
       {
           txtFilePath.Text = openFileDialog.FileName;
           ShowFileProperties(openFileDialog.FileName);
       }
    }
    private void ShowFileProperties(string filePath)
    {
        listView.Items.Clear();
        // Get the file info
        FileInfo fileInfo = new FileInfo(filePath);
        AddPropertyToListView("Dosya Yolu", fileInfo.FullName);
        AddPropertyToListView("Boyut", fileInfo.Length.ToString() + " byte");
        AddPropertyToListView("Yaratılış Zamanı", fileInfo.CreationTime.ToString());
        AddPropertyToListView("Son Erişim Zamanı", fileInfo.LastAccessTime.ToString());
        AddPropertyToListView("Son Yazma Zamanı", fileInfo.LastWriteTime.ToString());
        // Get the shell info
        Shell32.SHFILEINFO shinfo = new Shell32.SHFILEINFO();
        Shell32.SHGetFileInfo(filePath, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), Shell32.SHGFI_TYPENAME);
        AddPropertyToListView("Tür", shinfo.szTypeName);
    }
    private void AddPropertyToListView(string property, string value)
    {
        ListViewItem item = new ListViewItem(property);
        item.SubItems.Add(value);
        listView.Items.Add(item);
    }
}

3. Masaüstü Kısayol Oluşturucu
Belirli bir dosya veya uygulama için masaüstü kısayolu oluşturma.
C#:
using System;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Text;
using System.Windows.Forms;
C#:
private Button btnSelectFile;
private Button btnCreateShortcut;
private TextBox txtFilePath;
private TextBox txtShortcutName;
private OpenFileDialog openFileDialog;

public Main()
{
    InitializeComponent();
}

private void InitializeComponent()
{
    btnSelectFile = new Button();
    btnCreateShortcut = new Button();
    txtFilePath = new TextBox();
    txtShortcutName = new TextBox();
    openFileDialog = new OpenFileDialog();

    SuspendLayout();

    //
    // btnSelectFile
    //
    btnSelectFile.Location = new System.Drawing.Point(12, 12);
    btnSelectFile.Name = "btnSelectFile";
    btnSelectFile.Size = new System.Drawing.Size(75, 23);
    btnSelectFile.TabIndex = 0;
    btnSelectFile.Text = "Dosya Seçiniz";
    btnSelectFile.UseVisualStyleBackColor = true;
    btnSelectFile.Click += new EventHandler(BtnSelectFile_Click);

    //
    // btnCreateShortcut
    //
    btnCreateShortcut.Location = new System.Drawing.Point(12, 70);
    btnCreateShortcut.Name = "btnCreateShortcut";
    btnCreateShortcut.Size = new System.Drawing.Size(100, 23);
    btnCreateShortcut.TabIndex = 1;
    btnCreateShortcut.Text = "Kısayol Oluştur";
    btnCreateShortcut.UseVisualStyleBackColor = true;
    btnCreateShortcut.Click += new EventHandler(BtnCreateShortcut_Click);

    //
    // txtFilePath
    //
    txtFilePath.Location = new System.Drawing.Point(93, 14);
    txtFilePath.Name = "txtFilePath";
    txtFilePath.Size = new System.Drawing.Size(300, 20);
    txtFilePath.TabIndex = 2;

    //
    // txtShortcutName
    //
    txtShortcutName.Location = new System.Drawing.Point(93, 43);
    txtShortcutName.Name = "txtShortcutName";
    txtShortcutName.Size = new System.Drawing.Size(300, 20);
    txtShortcutName.TabIndex = 3;
    txtShortcutName.Text = "Kısayol Adı";

    //
    // Main
    //
    ClientSize = new System.Drawing.Size(405, 105);
    Controls.Add(txtShortcutName);
    Controls.Add(txtFilePath);
    Controls.Add(btnCreateShortcut);
    Controls.Add(btnSelectFile);
    Name = "Main";
    Text = "Masaüstü Kısayol Oluşturucu";
    StartPosition = FormStartPosition.CenterScreen;
    FormBorderStyle = FormBorderStyle.FixedSingle;
    MaximizeBox = false;
    ResumeLayout(false);
    PerformLayout();

}

private void BtnSelectFile_Click(object sender, EventArgs e)
{
    if (openFileDialog.ShowDialog() == DialogResult.OK)
    {
        txtFilePath.Text = openFileDialog.FileName;
    }
}

private void BtnCreateShortcut_Click(object sender, EventArgs e)
{
    string filePath = txtFilePath.Text;
    string shortcutName = txtShortcutName.Text;

    if (string.IsNullOrEmpty(filePath) || string.IsNullOrEmpty(shortcutName))
    {
        MessageBox.Show("Lütfen bir dosya seçin ve bir kısayol adı girin.");
        return;
    }

    CreateShortcut(filePath, shortcutName);
    MessageBox.Show("Kısayol başarıyla oluşturuldu!");
}

private void CreateShortcut(string filePath, string shortcutName)
{
    IShellLink link = (IShellLink)new ShellLink();
    link.SetPath(filePath);
    link.SetDescription(shortcutName);

    IPersistFile file = (IPersistFile)link;
    string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
    string shortcutPath = System.IO.Path.Combine(desktopPath, shortcutName + ".lnk");

    file.Save(shortcutPath, false);
}

[ComImport]
[Guid("00021401-0000-0000-C000-000000000046")]
internal class ShellLink
{
}

[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("000214F9-0000-0000-C000-000000000046")]
internal interface IShellLink
{
    void GetPath([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszFile, int cchMaxPath, out IntPtr pfd, int fFlags);
    void GetIDList(out IntPtr ppidl);
    void SetIDList(IntPtr pidl);
    void GetDescription([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszName, int cchMaxName);
    void SetDescription([MarshalAs(UnmanagedType.LPWStr)] string pszName);
    void GetWorkingDirectory([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszDir, int cchMaxPath);
    void SetWorkingDirectory([MarshalAs(UnmanagedType.LPWStr)] string pszDir);
    void GetArguments([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszArgs, int cchMaxPath);
    void SetArguments([MarshalAs(UnmanagedType.LPWStr)] string pszArgs);
    void GetHotkey(out short pwHotkey);
    void SetHotkey(short wHotkey);
    void GetShowCmd(out int piShowCmd);
    void SetShowCmd(int iShowCmd);
    void GetIconLocation([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszIconPath, int cchIconPath, out int piIcon);
    void SetIconLocation([MarshalAs(UnmanagedType.LPWStr)] string pszIconPath, int iIcon);
    void SetRelativePath([MarshalAs(UnmanagedType.LPWStr)] string pszPathRel, int dwReserved);
    void Resolve(IntPtr hwnd, int fFlags);
    void SetPath([MarshalAs(UnmanagedType.LPWStr)] string pszFile);
}

4. Geri Dönüşüm Kutusu Yönetimi
Geri Dönüşüm Kutusu'ndaki dosyaları listeleme, boşaltma ve geri yükleme işlemlerini gerçekleştirme.
C#:
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Shell32;
C#:
[DllImport("shell32.dll", CharSet = CharSet.Unicode)]
public static extern uint SHEmptyRecycleBin(IntPtr hwnd, string pszRootPath, uint dwFlags);

const uint SHERB_NOCONFIRMATION = 0x00000001;
const uint SHERB_NOPROGRESSUI = 0x00000002;
const uint SHERB_NOSOUND = 0x00000004;

public Main()
{
    InitializeComponent();
}

private void btnListItems_Click(object sender, EventArgs e)
{
    listBoxRecycleBin.Items.Clear();

    Shell shell = new Shell();
    Folder recycleBin = shell.NameSpace(10);

    foreach (FolderItem2 item in recycleBin.Items())
    {
        listBoxRecycleBin.Items.Add(item.Name);
    }
}

private void btnRestoreItem_Click(object sender, EventArgs e)
{
    if (listBoxRecycleBin.SelectedItem != null)
    {
        string selectedItemName = listBoxRecycleBin.SelectedItem.ToString();

        Shell shell = new Shell();
        Folder recycleBin = shell.NameSpace(10);

        foreach (FolderItem2 item in recycleBin.Items())
        {
            if (item.Name == selectedItemName)
            {
                item.InvokeVerb("RESTORE");
                MessageBox.Show($"{selectedItemName} geri yüklendi.");
                listBoxRecycleBin.Items.Remove(selectedItemName);
                break;
            }
        }
    }
    else
    {
        MessageBox.Show("Lütfen geri yüklemek için bir öğe seçin.", "HATA", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

private void btnDeleteItem_Click(object sender, EventArgs e)
{
    if (listBoxRecycleBin.SelectedItem != null)
    {
        string selectedItemName = listBoxRecycleBin.SelectedItem.ToString();

        Shell shell = new Shell();
        Folder recycleBin = shell.NameSpace(10);

        foreach (FolderItem2 item in recycleBin.Items())
        {
            if (item.Name == selectedItemName)
            {
                item.InvokeVerb("DELETE");
                MessageBox.Show($"{selectedItemName} kalıcı olarak silinmiştir.");
                listBoxRecycleBin.Items.Remove(selectedItemName);
                break;
            }
        }
    }
    else
    {
        MessageBox.Show("Lütfen silmek için bir öğe seçin.", "HATA", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

private void btnEmptyRecycleBin_Click(object sender, EventArgs e)
{
    uint result = SHEmptyRecycleBin(IntPtr.Zero, null, SHERB_NOCONFIRMATION);

    if (result == 0)
    {
        MessageBox.Show("Geri Dönüşüm Kutusu başarıyla boşaltıldı.");
        listBoxRecycleBin.Items.Clear();
    }
    else
    {
        MessageBox.Show($"Geri Dönüşüm Kutusu boşaltılırken bir hata oluştu. Hata kodu: {result}", "HATA", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

private void InitializeComponent()
{
    btnListItems = new Button();
    btnRestoreItem = new Button();
    btnDeleteItem = new Button();
    btnEmptyRecycleBin = new Button();
    listBoxRecycleBin = new ListBox();
    SuspendLayout();
    //
    // btnListItems
    //
    btnListItems.Location = new System.Drawing.Point(12, 12);
    btnListItems.Name = "btnListItems";
    btnListItems.Size = new System.Drawing.Size(180, 23);
    btnListItems.TabIndex = 0;
    btnListItems.Text = "Öğeleri Listele";
    btnListItems.UseVisualStyleBackColor = true;
    btnListItems.Click += new EventHandler(btnListItems_Click);
    //
    // btnRestoreItem
    //
    btnRestoreItem.Location = new System.Drawing.Point(12, 41);
    btnRestoreItem.Name = "btnRestoreItem";
    btnRestoreItem.Size = new System.Drawing.Size(180, 23);
    btnRestoreItem.TabIndex = 1;
    btnRestoreItem.Text = "Seçili Öğeyi Geri Yükle";
    btnRestoreItem.UseVisualStyleBackColor = true;
    btnRestoreItem.Click += new EventHandler(btnRestoreItem_Click);
    //
    // btnDeleteItem
    //
    btnDeleteItem.Location = new System.Drawing.Point(12, 70);
    btnDeleteItem.Name = "btnDeleteItem";
    btnDeleteItem.Size = new System.Drawing.Size(180, 23);
    btnDeleteItem.TabIndex = 2;
    btnDeleteItem.Text = "Seçili Öğeyi Sil";
    btnDeleteItem.UseVisualStyleBackColor = true;
    btnDeleteItem.Click += new EventHandler(btnDeleteItem_Click);
    //
    // btnEmptyRecycleBin
    //
    btnEmptyRecycleBin.Location = new System.Drawing.Point(12, 99);
    btnEmptyRecycleBin.Name = "btnEmptyRecycleBin";
    btnEmptyRecycleBin.Size = new System.Drawing.Size(180, 23);
    btnEmptyRecycleBin.TabIndex = 3;
    btnEmptyRecycleBin.Text = "Geri Dönüşüm Kutusunu Boşaltın";
    btnEmptyRecycleBin.UseVisualStyleBackColor = true;
    btnEmptyRecycleBin.Click += new EventHandler(btnEmptyRecycleBin_Click);
    //
    // listBoxRecycleBin
    //
    listBoxRecycleBin.FormattingEnabled = true;
    listBoxRecycleBin.Location = new System.Drawing.Point(198, 12);
    listBoxRecycleBin.Name = "listBoxRecycleBin";
    listBoxRecycleBin.Size = new System.Drawing.Size(260, 108);
    listBoxRecycleBin.TabIndex = 4;
    //
    // Main
    //
    AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
    AutoScaleMode = AutoScaleMode.Font;
    ClientSize = new System.Drawing.Size(484, 141);
    Controls.Add(listBoxRecycleBin);
    Controls.Add(btnEmptyRecycleBin);
    Controls.Add(btnDeleteItem);
    Controls.Add(btnRestoreItem);
    Controls.Add(btnListItems);
    Name = "Main";
    Text = "Geri Dönüşüm Kutusu Yöneticisi";
    StartPosition = FormStartPosition.CenterScreen;
    FormBorderStyle = FormBorderStyle.FixedSingle;
    MaximizeBox = false;

    ResumeLayout(false);

}

private Button btnListItems;
private Button btnRestoreItem;
private Button btnDeleteItem;
private Button btnEmptyRecycleBin;
private ListBox listBoxRecycleBin;

5. Dosya Kopyalama ve Taşıma
Dosya ve klasörleri kopyalama ve taşıma işlemlerini gerçekleştiren bir uygulama oluşturma.
C#:
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
C#:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
private struct SHFILEOPSTRUCT
{
    public IntPtr hwnd;
    [MarshalAs(UnmanagedType.U4)]
    public int wFunc;
    public string pFrom;
    public string pTo;
    public short fFlags;
    [MarshalAs(UnmanagedType.Bool)]
    public bool fAnyOperationsAborted;
    public IntPtr hNameMappings;
    public string lpszProgressTitle;
}

private const int FO_COPY = 0x0002;
private const int FO_MOVE = 0x0001;
private const int FOF_NOCONFIRMATION = 0x0010;
private const int FOF_SIMPLEPROGRESS = 0x0100;

[DllImport("shell32.dll", CharSet = CharSet.Auto)]
        private static extern int SHFileOperation(ref SHFILEOPSTRUCT FileOp);

public Main()
{
    InitializeComponent();
}

private void InitializeComponent()
{
    btnSelectSource = new Button();
    btnSelectDestination = new Button();
    btnCopy = new Button();
    btnMove = new Button();
    txtSource = new TextBox();
    txtDestination = new TextBox();
    SuspendLayout();
    //
    // btnSelectSource
    //
    btnSelectSource.Location = new Point(12, 12);
    btnSelectSource.Name = "btnSelectSource";
    btnSelectSource.Size = new Size(150, 23);
    btnSelectSource.TabIndex = 0;
    btnSelectSource.Text = "Kaynak Seçiniz";
    btnSelectSource.UseVisualStyleBackColor = true;
    btnSelectSource.Click += new EventHandler(btnSelectSource_Click);
    //
    // btnSelectDestination
    //
    btnSelectDestination.Location = new Point(12, 41);
    btnSelectDestination.Name = "btnSelectDestination";
    btnSelectDestination.Size = new Size(150, 23);
    btnSelectDestination.TabIndex = 1;
    btnSelectDestination.Text = "Hedef Seçin";
    btnSelectDestination.UseVisualStyleBackColor = true;
    btnSelectDestination.Click += new EventHandler(btnSelectDestination_Click);
    //
    // btnCopy
    //
    btnCopy.Location = new Point(12, 70);
    btnCopy.Name = "btnCopy";
    btnCopy.Size = new Size(150, 23);
    btnCopy.TabIndex = 2;
    btnCopy.Text = "Kopyala";
    btnCopy.UseVisualStyleBackColor = true;
    btnCopy.Click += new EventHandler(btnCopy_Click);
    //
    // btnMove
    //
    btnMove.Location = new Point(12, 99);
    btnMove.Name = "btnMove";
    btnMove.Size = new Size(150, 23);
    btnMove.TabIndex = 3;
    btnMove.Text = "Taşı";
    btnMove.UseVisualStyleBackColor = true;
    btnMove.Click += new EventHandler(btnMove_Click);
    //
    // txtSource
    //
    txtSource.Location = new Point(168, 14);
    txtSource.Name = "txtSource";
    txtSource.ReadOnly = true;
    txtSource.Size = new Size(300, 20);
    txtSource.TabIndex = 4;
    //
    // txtDestination
    //
    txtDestination.Location = new Point(168, 43);
    txtDestination.Name = "txtDestination";
    txtDestination.ReadOnly = true;
    txtDestination.Size = new Size(300, 20);
    txtDestination.TabIndex = 5;
    //
    // Main
    //
    AutoScaleDimensions = new SizeF(6F, 13F);
    AutoScaleMode = AutoScaleMode.Font;
    ClientSize = new Size(484, 141);
    Controls.Add(txtDestination);
    Controls.Add(txtSource);
    Controls.Add(btnMove);
    Controls.Add(btnCopy);
    Controls.Add(btnSelectDestination);
    Controls.Add(btnSelectSource);
    Name = "Main";
    Text = "Dosya İşlem Yöneticisi";
    StartPosition = FormStartPosition.CenterScreen;
    FormBorderStyle = FormBorderStyle.FixedSingle;
    MaximizeBox = false;
    ResumeLayout(false);
    PerformLayout();

}

private Button btnSelectSource;
private Button btnSelectDestination;
private Button btnCopy;
private Button btnMove;
private TextBox txtSource;
private TextBox txtDestination;

private void btnSelectSource_Click(object sender, EventArgs e)
{
    using (OpenFileDialog openFileDialog = new OpenFileDialog())
    {
        if (openFileDialog.ShowDialog() == DialogResult.OK)
        {
            txtSource.Text = openFileDialog.FileName;
        }
    }
}

private void btnSelectDestination_Click(object sender, EventArgs e)
{
    using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog())
    {
        if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
        {
            txtDestination.Text = folderBrowserDialog.SelectedPath;
        }
    }
}

private void btnCopy_Click(object sender, EventArgs e)
{
    PerformFileOperation(FO_COPY);
}

private void btnMove_Click(object sender, EventArgs e)
{
    PerformFileOperation(FO_MOVE);
}

private void PerformFileOperation(int operation)
{
    SHFILEOPSTRUCT fileOp = new SHFILEOPSTRUCT
    {
        wFunc = operation,
        pFrom = txtSource.Text + '\0' + '\0',
        pTo = txtDestination.Text + '\0' + '\0',
        fFlags = FOF_NOCONFIRMATION | FOF_SIMPLEPROGRESS
        };

    int result = SHFileOperation(ref fileOp);

    if (result == 0)
    {
        MessageBox.Show(operation == FO_COPY ? "Kopyalama işlemi başarıyla tamamlandı." : "Taşıma işlemi başarıyla tamamlanmıştır.");
    }
    else
    {
        MessageBox.Show($"İşlem sırasında bir hata oluştu. Hata kodu: {result}", "HATA", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

6. Sistem Simgeleri Gösterme
Dosya türlerine göre sistemdeki simgeleri gösterme.
C#:
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
C#:
[StructLayout(LayoutKind.Sequential)]
private struct SHFILEINFO
{
    public IntPtr hIcon;
    public int iIcon;
    public uint dwAttributes;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
    public string szDisplayName;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
    public string szTypeName;
}

private const uint SHGFI_ICON = 0x000000100;
private const uint SHGFI_LARGEICON = 0x000000000;
private const uint SHGFI_SMALLICON = 0x000000001;
private const uint SHGFI_USEFILEATTRIBUTES = 0x000000010;

[DllImport("shell32.dll", CharSet = CharSet.Auto)]
        private static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbFileInfo, uint uFlags);

public Main()
{
    InitializeComponent();
}

private void InitializeComponent()
{
    btnSelectFile = new Button();
    pictureBoxIcon = new PictureBox();
    ((System.ComponentModel.ISupportInitialize)(pictureBoxIcon)).BeginInit();
    SuspendLayout();
    //
    // btnSelectFile
    //
    btnSelectFile.Location = new Point(16, 15);
    btnSelectFile.Margin = new Padding(4, 4, 4, 4);
    btnSelectFile.Name = "btnSelectFile";
    btnSelectFile.Size = new Size(200, 28);
    btnSelectFile.TabIndex = 0;
    btnSelectFile.Text = "Dosya Seçiniz";
    btnSelectFile.UseVisualStyleBackColor = true;
    btnSelectFile.Click += new System.EventHandler(btnSelectFile_Click);
    //
    // pictureBoxIcon
    //
    pictureBoxIcon.Location = new Point(16, 50);
    pictureBoxIcon.Margin = new Padding(4, 4, 4, 4);
    pictureBoxIcon.Name = "pictureBoxIcon";
    pictureBoxIcon.Size = new Size(32, 32);
    pictureBoxIcon.SizeMode = PictureBoxSizeMode.AutoSize;
    pictureBoxIcon.TabIndex = 1;
    pictureBoxIcon.TabStop = false;
    //
    // Main
    //
    AutoScaleDimensions = new SizeF(8F, 16F);
    AutoScaleMode = AutoScaleMode.Font;
    ClientSize = new Size(450, 110);
    Controls.Add(pictureBoxIcon);
    Controls.Add(btnSelectFile);
    Margin = new Padding(4, 4, 4, 4);
    Name = "Main";
    Text = "Dosya Simgesi Görüntüleyicisi";
    StartPosition = FormStartPosition.CenterScreen;
    FormBorderStyle = FormBorderStyle.FixedSingle;
    MaximizeBox = false;
    ((System.ComponentModel.ISupportInitialize)(pictureBoxIcon)).EndInit();
    ResumeLayout(false);
    PerformLayout();

}

private Button btnSelectFile;
private PictureBox pictureBoxIcon;

private void btnSelectFile_Click(object sender, EventArgs e)
{
    using (OpenFileDialog openFileDialog = new OpenFileDialog())
    {
        if (openFileDialog.ShowDialog() == DialogResult.OK)
        {
            string filePath = openFileDialog.FileName;
            DisplayFileIcon(filePath);
        }
    }
}

private void DisplayFileIcon(string filePath)
{
    SHFILEINFO shinfo = new SHFILEINFO();
    IntPtr hImgSmall = SHGetFileInfo(filePath, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), SHGFI_ICON | SHGFI_LARGEICON);

    if (hImgSmall != IntPtr.Zero)
    {
        Icon icon = Icon.FromHandle(shinfo.hIcon);
        pictureBoxIcon.Image = icon.ToBitmap();
        DestroyIcon(shinfo.hIcon);
    }
}

[DllImport("user32.dll", CharSet = CharSet.Auto)]
extern static bool DestroyIcon(IntPtr handle);



C-842602893.png


User32 API: Pencere ve Kullanıcı Girdisi Yönetiminde Profesyonel Araçlar

User32 API, Windows işletim sistemi içinde pencere oluşturma, yönetme ve kullanıcı girdisini işleme gibi görevleri üstlenen güçlü bir araçtır. Bu API, grafik kullanıcı arayüzü (GUI) uygulamaları geliştirmek için bir dizi fonksiyon sağlar.

Bu konuda, User32 API'nin temel yeteneklerini ve pratik kullanımını keşfetmek için adım adım ilerleyeceğiz. User32 API'nin sunduğu araçlarla pencere oluşturma, girdi işleme, pencere hareketleri ve daha fazlasını gerçekleştireceğiz.


Projeler

1. Basit Pencere Yönetimi Uygulaması
Kullanıcıya açılan pencereleri listeleme, küçültme, büyütme veya kapatma yetenekleri sağlamak.
C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace Terganca
{
    public class WindowManager
    {
        [DllImport("user32.dll", SetLastError = true)]
        private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll", SetLastError = true)]
        private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

        [DllImport("user32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);

        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);

        [DllImport("user32.dll", SetLastError = true)]
        private static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);

        [DllImport("user32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool IsWindowVisible(IntPtr hWnd);

        private const int SW_MINIMIZE = 6;
        private const int SW_MAXIMIZE = 3;
        private const int SW_RESTORE = 9;

        private delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);

        public static List<WindowInfo> GetOpenWindows()
        {
            var windows = new List<WindowInfo>();

            EnumWindows((hWnd, lParam) =>
            {
                if (IsWindowVisible(hWnd))
                {
                    var length = GetWindowTextLength(hWnd);
                    if (length > 0)
                    {
                        var builder = new StringBuilder(length);
                        GetWindowText(hWnd, builder, length + 1);
                        windows.Add(new WindowInfo { Handle = hWnd, Title = builder.ToString() });
                    }
                }
                return true;
            }, IntPtr.Zero);

            return windows;
        }

        public static void MinimizeWindow(IntPtr hWnd)
        {
            ShowWindow(hWnd, SW_MINIMIZE);
        }

        public static void MaximizeWindow(IntPtr hWnd)
        {
            ShowWindow(hWnd, SW_MAXIMIZE);
        }

        public static void RestoreWindow(IntPtr hWnd)
        {
            ShowWindow(hWnd, SW_RESTORE);
        }

        public static void BringToFront(IntPtr hWnd)
        {
            SetForegroundWindow(hWnd);
        }

        private static int GetWindowTextLength(IntPtr hWnd)
        {
            return SendMessage(hWnd, WM_GETTEXTLENGTH, IntPtr.Zero, IntPtr.Zero).ToInt32();
        }

        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

        private const uint WM_GETTEXTLENGTH = 0x000E;

        public class WindowInfo
        {
            public IntPtr Handle { get; set; }
            public string Title { get; set; }
        }
    }
}
C#:
public partial class Main : Form
{
    private ListBox lstWindows;
    private Button btnRefresh;
    private Button btnMinimize;
    private Button btnMaximize;
    private Button btnRestore;
    private Button btnBringToFront;

    public Main()
    {
        InitializeComponent();
    }

    private void InitializeComponent()
    {
        lstWindows = new ListBox();
        btnRefresh = new Button();
        btnMinimize = new Button();
        btnMaximize = new Button();
        btnRestore = new Button();
        btnBringToFront = new Button();

        SuspendLayout();

        //
        // lstWindows
        //
        lstWindows.FormattingEnabled = true;
        lstWindows.Location = new System.Drawing.Point(12, 12);
        lstWindows.Name = "lstWindows";
        lstWindows.Size = new System.Drawing.Size(396, 199);
        lstWindows.TabIndex = 0;

        //
        // btnRefresh
        //
        btnRefresh.Location = new System.Drawing.Point(12, 217);
        btnRefresh.Name = "btnRefresh";
        btnRefresh.Size = new System.Drawing.Size(75, 23);
        btnRefresh.TabIndex = 1;
        btnRefresh.Text = "Yenile";
        btnRefresh.UseVisualStyleBackColor = true;
        btnRefresh.Click += new EventHandler(BtnRefresh_Click);

        //
        // btnMinimize
        //
        btnMinimize.Location = new System.Drawing.Point(93, 217);
        btnMinimize.Name = "btnMinimize";
        btnMinimize.Size = new System.Drawing.Size(75, 23);
        btnMinimize.TabIndex = 2;
        btnMinimize.Text = "Minimize et";
        btnMinimize.UseVisualStyleBackColor = true;
        btnMinimize.Click += new EventHandler(BtnMinimize_Click);

        //
        // btnMaximize
        //
        btnMaximize.Location = new System.Drawing.Point(174, 217);
        btnMaximize.Name = "btnMaximize";
        btnMaximize.Size = new System.Drawing.Size(75, 23);
        btnMaximize.TabIndex = 3;
        btnMaximize.Text = "Maksimize Et";
        btnMaximize.UseVisualStyleBackColor = true;
        btnMaximize.Click += new EventHandler(BtnMaximize_Click);

        //
        // btnRestore
        //
        btnRestore.Location = new System.Drawing.Point(255, 217);
        btnRestore.Name = "btnRestore";
        btnRestore.Size = new System.Drawing.Size(75, 23);
        btnRestore.TabIndex = 4;
        btnRestore.Text = "Geri Yükle";
        btnRestore.UseVisualStyleBackColor = true;
        btnRestore.Click += new EventHandler(BtnRestore_Click);

        //
        // btnBringToFront
        //
        btnBringToFront.Location = new System.Drawing.Point(336, 217);
        btnBringToFront.Name = "btnBringToFront";
        btnBringToFront.Size = new System.Drawing.Size(75, 23);
        btnBringToFront.TabIndex = 5;
        btnBringToFront.Text = "Öne Getir";
        btnBringToFront.UseVisualStyleBackColor = true;
        btnBringToFront.Click += new EventHandler(BtnBringToFront_Click);

        //
        // Main
        //
        ClientSize = new System.Drawing.Size(424, 251);
        Controls.Add(btnBringToFront);
        Controls.Add(btnRestore);
        Controls.Add(btnMaximize);
        Controls.Add(btnMinimize);
        Controls.Add(btnRefresh);
        Controls.Add(lstWindows);
        Name = "Main";
        Text = "Pencere Yöneticisi";
        Load += new EventHandler(Main_Load);
        StartPosition = FormStartPosition.CenterScreen;
        FormBorderStyle = FormBorderStyle.FixedSingle;
        MaximizeBox = false;
        ResumeLayout(false);
    }

    private void Main_Load(object sender, EventArgs e)
    {
        RefreshWindowList();
    }

    private void BtnRefresh_Click(object sender, EventArgs e)
    {
        RefreshWindowList();
    }

    private void BtnMinimize_Click(object sender, EventArgs e)
    {
        if (lstWindows.SelectedItem is WindowManager.WindowInfo selectedWindow)
        {
            WindowManager.MinimizeWindow(selectedWindow.Handle);
        }
    }

    private void BtnMaximize_Click(object sender, EventArgs e)
    {
        if (lstWindows.SelectedItem is WindowManager.WindowInfo selectedWindow)
        {
            WindowManager.MaximizeWindow(selectedWindow.Handle);
        }
    }

    private void BtnRestore_Click(object sender, EventArgs e)
    {
        if (lstWindows.SelectedItem is WindowManager.WindowInfo selectedWindow)
        {
            WindowManager.RestoreWindow(selectedWindow.Handle);
        }
    }

    private void BtnBringToFront_Click(object sender, EventArgs e)
    {
        if (lstWindows.SelectedItem is WindowManager.WindowInfo selectedWindow)
        {
            WindowManager.BringToFront(selectedWindow.Handle);
        }
    }

    private void RefreshWindowList()
    {
        var windows = WindowManager.GetOpenWindows();
        lstWindows.DataSource = windows;
        lstWindows.DisplayMember = "Title";
    }
}

2. Ekran Koordinatlarını İzleme
Fare imlecinin ekran üzerindeki koordinatlarını gerçek zamanlı olarak gösterme.
C#:
using System.Runtime.InteropServices;

public class CursorTrackerFunction
{
    [DllImport("user32.dll")]
    private static extern bool GetCursorPos(out POINT lpPoint);

    public struct POINT
    {
        public int X;
        public int Y;
    }

    public static POINT GetCursorPosition()
    {
        GetCursorPos(out POINT lpPoint);
        return lpPoint;
    }
}
C#:
public partial class Main : Form
{
    private Label lblCoordinates;
    private Timer timer;

    public Main()
    {
        InitializeComponent();
    }

    private void InitializeComponent()
    {
        lblCoordinates = new Label();
        timer = new Timer();

        SuspendLayout();

        //
        // lblCoordinates
        //
        lblCoordinates.AutoSize = true;
        lblCoordinates.Location = new System.Drawing.Point(12, 9);
        lblCoordinates.Name = "lblCoordinates";
        lblCoordinates.Size = new System.Drawing.Size(100, 23);
        lblCoordinates.TabIndex = 0;
        lblCoordinates.Text = "X: 0, Y: 0";

        //
        // timer
        //
        timer.Interval = 100;
        timer.Tick += new EventHandler(Timer_Tick);

        //
        // Main
        //
        ClientSize = new System.Drawing.Size(284, 41);
        Controls.Add(lblCoordinates);
        Name = "Main";
        Text = "Fare Koordinat İzleyici";
        Load += new EventHandler(MainForm_Load);
        StartPosition = FormStartPosition.CenterScreen;
        MaximizeBox = false;
        FormBorderStyle = FormBorderStyle.FixedSingle;
        ResumeLayout(false);
        PerformLayout();
    }

    private void MainForm_Load(object sender, EventArgs e)
    {
        timer.Start();
    }

    private void Timer_Tick(object sender, EventArgs e)
    {
        var position = CursorTrackerFunction.GetCursorPosition();
        lblCoordinates.Text = $"X: {position.X}, Y: {position.Y}";
    }
}

3. Klavye Tuşlarını Dinleme
Kullanıcının bastığı tuşları izleme ve kaydetme.
C#:
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;

public class KeyboardHookFunction
{
    private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
    private LowLevelKeyboardProc _proc;
    private IntPtr _hookID = IntPtr.Zero;

    public KeyboardHookFunction()
    {
        _proc = HookCallback;
    }

    public void HookKeyboard()
    {
        _hookID = SetHook(_proc);
    }

    public void UnhookKeyboard()
    {
        UnhookWindowsHookEx(_hookID);
    }

    private IntPtr SetHook(LowLevelKeyboardProc proc)
    {
        using (var curProcess = Process.GetCurrentProcess())
        using (var curModule = curProcess.MainModule)
        {
            return SetWindowsHookEx(WH_KEYBOARD_LL, proc, GetModuleHandle(curModule.ModuleName), 0);
        }
    }

    private IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
    {
        if (nCode >= 0 && (wParam == (IntPtr)WM_KEYDOWN || wParam == (IntPtr)WM_SYSKEYDOWN))
        {
            int vkCode = Marshal.ReadInt32(lParam);
            KeyPressed?.Invoke(this, (Keys)vkCode);
        }
        return CallNextHookEx(_hookID, nCode, wParam, lParam);
    }

    public event EventHandler<Keys> KeyPressed;

    private const int WH_KEYBOARD_LL = 13;
    private const int WM_KEYDOWN = 0x0100;
    private const int WM_SYSKEYDOWN = 0x0104;

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool UnhookWindowsHookEx(IntPtr hhk);

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr GetModuleHandle(string lpModuleName);
}
C#:
public partial class Main : Form
{
    private TextBox txtKeyLogger;
    private Button btnStart;
    private Button btnStop;
    private KeyboardHookFunction _keyboardHook;

    public Main()
    {
        InitializeComponent();
        _keyboardHook = new KeyboardHookFunction();
        _keyboardHook.KeyPressed += KeyboardHook_KeyPressed;
        btnStop.Enabled = false;
    }

    private void InitializeComponent()
    {
        txtKeyLogger = new TextBox();
        btnStart = new Button();
        btnStop = new Button();

        SuspendLayout();

        //
        // txtKeyLogger
        //
        txtKeyLogger.Location = new Point(12, 12);
        txtKeyLogger.Multiline = true;
        txtKeyLogger.Name = "txtKeyLogger";
        txtKeyLogger.Size = new Size(360, 199);
        txtKeyLogger.TabIndex = 0;
        txtKeyLogger.ReadOnly = true;

        //
        // btnStart
        //
        btnStart.Location = new Point(12, 217);
        btnStart.Name = "btnStart";
        btnStart.Size = new Size(75, 23);
        btnStart.TabIndex = 1;
        btnStart.Text = "Başlat";
        btnStart.UseVisualStyleBackColor = true;
        btnStart.Click += new EventHandler(BtnStart_Click);

        //
        // btnStop
        //
        btnStop.Location = new Point(93, 217);
        btnStop.Name = "btnStop";
        btnStop.Size = new Size(75, 23);
        btnStop.TabIndex = 2;
        btnStop.Text = "Durdur";
        btnStop.UseVisualStyleBackColor = true;
        btnStop.Click += new EventHandler(BtnStop_Click);

        //
        // Main
        //
        ClientSize = new Size(384, 251);
        Controls.Add(btnStop);
        Controls.Add(btnStart);
        Controls.Add(txtKeyLogger);
        Name = "Main";
        Text = "Tuş Kaydedici";
        StartPosition = FormStartPosition.CenterScreen;
        FormBorderStyle = FormBorderStyle.FixedSingle;
        MaximizeBox = false;
        ResumeLayout(false);
        PerformLayout();
    }

    private void BtnStart_Click(object sender, EventArgs e)
    {
        _keyboardHook.HookKeyboard();
        btnStart.Enabled = false;
        btnStop.Enabled = true;
    }

    private void BtnStop_Click(object sender, EventArgs e)
    {
        _keyboardHook.UnhookKeyboard();
        btnStart.Enabled = true;
        btnStop.Enabled = false;
    }

    private void KeyboardHook_KeyPressed(object sender, Keys e)
    {
        txtKeyLogger.AppendText(e.ToString() + " ");
    }
}

Konu 50.000 karakteri aştığı için devamı aşağıda ki mesajda devam ediyor..
 

Eratronos

Ar-Ge Ekibi
8 Kas 2021
191
12
129
(LPSTR)"dxeiz.exe";
4. Ekran Görüntüsü Alma
Kullanıcının ekranının tamamının veya belirli bir bölgesinin görüntüsünü alma ve kaydetme.
C#:
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.Windows.Forms;

public class ScreenCaptureFunction
{
    [DllImport("user32.dll")]
    private static extern IntPtr GetDC(IntPtr hwnd);

    [DllImport("user32.dll")]
    private static extern IntPtr ReleaseDC(IntPtr hwnd, IntPtr hdc);

    [DllImport("gdi32.dll")]
    private static extern IntPtr DeleteObject(IntPtr hObject);

    [DllImport("gdi32.dll")]
    private static extern bool BitBlt(IntPtr hdcDest, int nXDest, int nYDest, int nWidth, int nHeight,
        IntPtr hdcSrc, int nXSrc, int nYSrc, int dwRop);

    private const int SRCCOPY = 0x00CC0020;

    public static Bitmap CaptureScreen()
    {
        Rectangle bounds = Screen.PrimaryScreen.Bounds;
        Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height, PixelFormat.Format32bppArgb);

        using (Graphics graphics = Graphics.FromImage(bitmap))
        {
            IntPtr hdcDest = graphics.GetHdc();
            IntPtr hdcSrc = GetDC(IntPtr.Zero);
            BitBlt(hdcDest, 0, 0, bounds.Width, bounds.Height, hdcSrc, 0, 0, SRCCOPY);
            graphics.ReleaseHdc(hdcDest);
            ReleaseDC(IntPtr.Zero, hdcSrc);
        }

        return bitmap;
    }
}
C#:
public partial class Main : Form
{
    private PictureBox pictureBox;
    private Button btnCapture;
    private Button btnSave;
    private Button btnCopy;

    public Main()
    {
        InitializeComponent();
    }

    private void InitializeComponent()
    {
        pictureBox = new PictureBox();
        btnCapture = new Button();
        btnSave = new Button();
        btnCopy = new Button();

        SuspendLayout();

        //
        // pictureBox
        //
        pictureBox.Location = new Point(12, 12);
        pictureBox.Name = "pictureBox";
        pictureBox.Size = new Size(360, 199);
        pictureBox.SizeMode = PictureBoxSizeMode.Zoom;
        pictureBox.TabIndex = 0;
        pictureBox.TabStop = false;

        //
        // btnCapture
        //
        btnCapture.Location = new Point(12, 217);
        btnCapture.Name = "btnCapture";
        btnCapture.Size = new Size(75, 23);
        btnCapture.TabIndex = 1;
        btnCapture.Text = "Yakala";
        btnCapture.UseVisualStyleBackColor = true;
        btnCapture.Click += new EventHandler(BtnCapture_Click);

        //
        // btnSave
        //
        btnSave.Location = new Point(93, 217);
        btnSave.Name = "btnSave";
        btnSave.Size = new Size(75, 23);
        btnSave.TabIndex = 2;
        btnSave.Text = "Kaydet";
        btnSave.UseVisualStyleBackColor = true;
        btnSave.Click += new EventHandler(BtnSave_Click);

        //
        // btnCopy
        //
        btnCopy.Location = new Point(174, 217);
        btnCopy.Name = "btnCopy";
        btnCopy.Size = new Size(75, 23);
        btnCopy.TabIndex = 3;
        btnCopy.Text = "Kopyala";
        btnCopy.UseVisualStyleBackColor = true;
        btnCopy.Click += new EventHandler(BtnCopy_Click);

        //
        // Main
        //
        ClientSize = new Size(384, 251);
        Controls.Add(btnCopy);
        Controls.Add(btnSave);
        Controls.Add(btnCapture);
        Controls.Add(pictureBox);
        Name = "Main";
        Text = "Ekran Görüntüsü";
        StartPosition = FormStartPosition.CenterScreen;
        FormBorderStyle = FormBorderStyle.FixedSingle;
        MaximizeBox = false;
        ResumeLayout(false);
    }

    private void BtnCapture_Click(object sender, EventArgs e)
    {
        Bitmap screenshot = ScreenCaptureFunction.CaptureScreen();
        pictureBox.Image = screenshot;
    }

    private void BtnSave_Click(object sender, EventArgs e)
    {
        if (pictureBox.Image != null)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog
            {
                Filter = "PNG Image|*.png|JPEG Image|*.jpg|Bitmap Image|*.bmp",
                Title = "Ekran Görüntüsünü Kaydet"
            };

            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                string filePath = saveFileDialog.FileName;
                ImageFormat format = ImageFormat.Png;

                switch (System.IO.Path.GetExtension(filePath).ToLower())
                {
                    case ".jpg":
                        format = ImageFormat.Jpeg;
                        break;
                    case ".bmp":
                        format = ImageFormat.Bmp;
                        break;
                }

                pictureBox.Image.Save(filePath, format);
            }
        }
        else
        {
            MessageBox.Show("Kaydedilecek görüntü yok.", "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    private void BtnCopy_Click(object sender, EventArgs e)
    {
        if (pictureBox.Image != null)
        {
            Clipboard.SetImage(pictureBox.Image);
            MessageBox.Show("Ekran görüntüsü panoya kopyalandı.", "Başarılı", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        else
        {
            MessageBox.Show("Kopyalanacak görüntü yok.", "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
}

5. Fare ve Klavye Otomasyonu
Belirli görevleri otomatikleştirmek için fare ve klavye olaylarını simüle etme.
C#:
using System;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;

public class AutomationFunction
{
    [DllImport("user32.dll", SetLastError = true)]
    public static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);

    [DllImport("user32.dll")]
    public static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, UIntPtr dwExtraInfo);

    public const int MOUSEEVENTF_LEFTDOWN = 0x02;
    public const int MOUSEEVENTF_LEFTUP = 0x04;
    public const int MOUSEEVENTF_MOVE = 0x0001;

    public const int KEYEVENTF_KEYDOWN = 0x0000;
    public const int KEYEVENTF_KEYUP = 0x0002;

    public static void SimulateMouseClick(int x, int y)
    {
        SetCursorPosition(x, y);
        mouse_event(MOUSEEVENTF_LEFTDOWN, x, y, 0, 0);
        mouse_event(MOUSEEVENTF_LEFTUP, x, y, 0, 0);
    }

    public static void SetCursorPosition(int x, int y)
    {
        Cursor.Position = new System.Drawing.Point(x, y);
    }

    public static void SimulateKeyPress(byte keyCode)
    {
        keybd_event(keyCode, 0, KEYEVENTF_KEYDOWN, UIntPtr.Zero);
        Thread.Sleep(100);
        keybd_event(keyCode, 0, KEYEVENTF_KEYUP, UIntPtr.Zero);
    }
}
C#:
public partial class Main : Form
{
    public Main()
    {
        AutomationFunction.SimulateMouseClick(100, 100);    // x:100, y:100 ve tıkla
        AutomationFunction.SimulateKeyPress(0x41);          // 'A'
        InitializeComponent();

        Thread.Sleep(3000);
        Environment.Exit(0);
    }

    private void InitializeComponent()
    {
        SuspendLayout();
        //
        // Main
        //
        ClientSize = new System.Drawing.Size(0, 0);
        ControlBox = false;
        Enabled = false;
        FormBorderStyle = FormBorderStyle.None;
        MaximizeBox = false;
        MinimizeBox = false;
        Name = "Main";
        Opacity = 0D;
        ShowIcon = false;
        ShowInTaskbar = false;
        Text = "a";
        ResumeLayout(false);
    }
}

6. Ekran Renk Paleti Oluşturucu
Fare imlecinin bulunduğu noktadaki pikselin rengini tespit etme ve bir renk paleti oluşturma.
C#:
using System;
using System.Drawing;
using System.Runtime.InteropServices;

public class ColorPicker
{
    [DllImport("user32.dll")]
    private static extern bool GetCursorPos(out POINT lpPoint);

    [DllImport("gdi32.dll")]
    private static extern uint GetPixel(IntPtr hdc, int nXPos, int nYPos);

    [DllImport("user32.dll")]
    private static extern IntPtr GetDC(IntPtr hWnd);

    [DllImport("user32.dll")]
    private static extern IntPtr ReleaseDC(IntPtr hWnd, IntPtr hDC);

    public struct POINT
    {
        public int X;
        public int Y;
    }

    public static Color GetColorAtCursor()
    {
        POINT cursorPos;
        GetCursorPos(out cursorPos);

        IntPtr hdc = GetDC(IntPtr.Zero);
        uint pixel = GetPixel(hdc, cursorPos.X, cursorPos.Y);
        ReleaseDC(IntPtr.Zero, hdc);

        Color color = Color.FromArgb((int)(pixel & 0x000000FF),
                                     (int)(pixel & 0x0000FF00) >> 8,
                                     (int)(pixel & 0x00FF0000) >> 16);
        return color;
    }
}
C#:
public partial class Main : Form
{
    private Panel colorPanel;
    private ListBox colorListBox;
    private List<Color> colorPalette;
    private Timer timer;

    public Main()
    {
        InitializeComponent();
        colorPalette = new List<Color>();

        timer = new Timer();
        timer.Interval = 500;
        timer.Tick += Timer_Tick;
        timer.Start();
    }

    private void InitializeComponent()
    {
        colorPanel = new Panel();
        colorListBox = new ListBox();

        SuspendLayout();

        //
        // colorPanel
        //
        colorPanel.Location = new Point(12, 12);
        colorPanel.Name = "colorPanel";
        colorPanel.Size = new Size(50, 50);
        colorPanel.TabIndex = 1;
        colorPanel.BackColor = Color.White;

        //
        // colorListBox
        //
        colorListBox.FormattingEnabled = true;
        colorListBox.Location = new Point(12, 70);
        colorListBox.Name = "colorListBox";
        colorListBox.Size = new Size(200, 147);
        colorListBox.TabIndex = 2;

        //
        // Main
        //
        ClientSize = new Size(284, 261);
        Controls.Add(colorListBox);
        Controls.Add(colorPanel);
        Name = "Main";
        Text = "Renk Seçici";
        ResumeLayout(false);

    }

    private void Timer_Tick(object sender, EventArgs e)
    {
        Color color = ColorPicker.GetColorAtCursor();
        if (!colorPalette.Contains(color))
        {
            colorPanel.BackColor = color;
            colorPalette.Add(color);
            colorListBox.Items.Add(ColorTranslator.ToHtml(color));
        }
    }
}

Sonuç

User32 API, pencereleri oluştu͏rmak͏ ve kontrol etmek, kullanıcı girişini yönetmek ve pencere boyutunu, konumunu ve görün͏ümü͏nü değiştirmek ͏için işlevlere͏ sahipti͏r. Ku͏llanıcı etkileşimini yönetmek için͏ iyidir.
͏
Shell32 API, dosya ve sistem kontrolüne yönelik iş͏levl͏erden͏ oluşur. D͏osyalar͏ı yönetmeye, s͏istem simgeleri͏ni almaya,͏ geri dönüşüm ku͏tusu͏nu kontrol etmeye ve daha fa͏zlasına yardımcı olur. Bu AP͏I͏, dosya͏ yönetimi ve dosya sistemiyle etkileşim için kullanışl͏ı bir araçtır.


Bu API'leri kullanarak Windows işletim sist͏emi içeri͏sinde çeşitli projeler geliştirebilir ve görevleri oto͏matikle͏ş͏tirebilirsiniz͏. Projeleriniz üz͏erinde çalışırke͏n ͏API fonksiyonların͏ı ve özellikler͏ini etkili bir şek͏i͏lde kull͏anmak i͏çin pra͏tik yapmak ve den͏eyim kazanmak önemlidir.


Github Hesabım: github.com/DxeiZ
Projenin Github Kaynağı: github.com/DxeiZ/Terganca
 

şıkk

Üye
24 Eki 2023
120
57
4. Ekran Görüntüsü Alma
Kullanıcının ekranının tamamının veya belirli bir bölgesinin görüntüsünü alma ve kaydetme.
C#:
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.Windows.Forms;

public class ScreenCaptureFunction
{
    [DllImport("user32.dll")]
    private static extern IntPtr GetDC(IntPtr hwnd);

    [DllImport("user32.dll")]
    private static extern IntPtr ReleaseDC(IntPtr hwnd, IntPtr hdc);

    [DllImport("gdi32.dll")]
    private static extern IntPtr DeleteObject(IntPtr hObject);

    [DllImport("gdi32.dll")]
    private static extern bool BitBlt(IntPtr hdcDest, int nXDest, int nYDest, int nWidth, int nHeight,
        IntPtr hdcSrc, int nXSrc, int nYSrc, int dwRop);

    private const int SRCCOPY = 0x00CC0020;

    public static Bitmap CaptureScreen()
    {
        Rectangle bounds = Screen.PrimaryScreen.Bounds;
        Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height, PixelFormat.Format32bppArgb);

        using (Graphics graphics = Graphics.FromImage(bitmap))
        {
            IntPtr hdcDest = graphics.GetHdc();
            IntPtr hdcSrc = GetDC(IntPtr.Zero);
            BitBlt(hdcDest, 0, 0, bounds.Width, bounds.Height, hdcSrc, 0, 0, SRCCOPY);
            graphics.ReleaseHdc(hdcDest);
            ReleaseDC(IntPtr.Zero, hdcSrc);
        }

        return bitmap;
    }
}
C#:
public partial class Main : Form
{
    private PictureBox pictureBox;
    private Button btnCapture;
    private Button btnSave;
    private Button btnCopy;

    public Main()
    {
        InitializeComponent();
    }

    private void InitializeComponent()
    {
        pictureBox = new PictureBox();
        btnCapture = new Button();
        btnSave = new Button();
        btnCopy = new Button();

        SuspendLayout();

        //
        // pictureBox
        //
        pictureBox.Location = new Point(12, 12);
        pictureBox.Name = "pictureBox";
        pictureBox.Size = new Size(360, 199);
        pictureBox.SizeMode = PictureBoxSizeMode.Zoom;
        pictureBox.TabIndex = 0;
        pictureBox.TabStop = false;

        //
        // btnCapture
        //
        btnCapture.Location = new Point(12, 217);
        btnCapture.Name = "btnCapture";
        btnCapture.Size = new Size(75, 23);
        btnCapture.TabIndex = 1;
        btnCapture.Text = "Yakala";
        btnCapture.UseVisualStyleBackColor = true;
        btnCapture.Click += new EventHandler(BtnCapture_Click);

        //
        // btnSave
        //
        btnSave.Location = new Point(93, 217);
        btnSave.Name = "btnSave";
        btnSave.Size = new Size(75, 23);
        btnSave.TabIndex = 2;
        btnSave.Text = "Kaydet";
        btnSave.UseVisualStyleBackColor = true;
        btnSave.Click += new EventHandler(BtnSave_Click);

        //
        // btnCopy
        //
        btnCopy.Location = new Point(174, 217);
        btnCopy.Name = "btnCopy";
        btnCopy.Size = new Size(75, 23);
        btnCopy.TabIndex = 3;
        btnCopy.Text = "Kopyala";
        btnCopy.UseVisualStyleBackColor = true;
        btnCopy.Click += new EventHandler(BtnCopy_Click);

        //
        // Main
        //
        ClientSize = new Size(384, 251);
        Controls.Add(btnCopy);
        Controls.Add(btnSave);
        Controls.Add(btnCapture);
        Controls.Add(pictureBox);
        Name = "Main";
        Text = "Ekran Görüntüsü";
        StartPosition = FormStartPosition.CenterScreen;
        FormBorderStyle = FormBorderStyle.FixedSingle;
        MaximizeBox = false;
        ResumeLayout(false);
    }

    private void BtnCapture_Click(object sender, EventArgs e)
    {
        Bitmap screenshot = ScreenCaptureFunction.CaptureScreen();
        pictureBox.Image = screenshot;
    }

    private void BtnSave_Click(object sender, EventArgs e)
    {
        if (pictureBox.Image != null)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog
            {
                Filter = "PNG Image|*.png|JPEG Image|*.jpg|Bitmap Image|*.bmp",
                Title = "Ekran Görüntüsünü Kaydet"
            };

            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                string filePath = saveFileDialog.FileName;
                ImageFormat format = ImageFormat.Png;

                switch (System.IO.Path.GetExtension(filePath).ToLower())
                {
                    case ".jpg":
                        format = ImageFormat.Jpeg;
                        break;
                    case ".bmp":
                        format = ImageFormat.Bmp;
                        break;
                }

                pictureBox.Image.Save(filePath, format);
            }
        }
        else
        {
            MessageBox.Show("Kaydedilecek görüntü yok.", "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    private void BtnCopy_Click(object sender, EventArgs e)
    {
        if (pictureBox.Image != null)
        {
            Clipboard.SetImage(pictureBox.Image);
            MessageBox.Show("Ekran görüntüsü panoya kopyalandı.", "Başarılı", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        else
        {
            MessageBox.Show("Kopyalanacak görüntü yok.", "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
}

5. Fare ve Klavye Otomasyonu
Belirli görevleri otomatikleştirmek için fare ve klavye olaylarını simüle etme.
C#:
using System;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;

public class AutomationFunction
{
    [DllImport("user32.dll", SetLastError = true)]
    public static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);

    [DllImport("user32.dll")]
    public static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, UIntPtr dwExtraInfo);

    public const int MOUSEEVENTF_LEFTDOWN = 0x02;
    public const int MOUSEEVENTF_LEFTUP = 0x04;
    public const int MOUSEEVENTF_MOVE = 0x0001;

    public const int KEYEVENTF_KEYDOWN = 0x0000;
    public const int KEYEVENTF_KEYUP = 0x0002;

    public static void SimulateMouseClick(int x, int y)
    {
        SetCursorPosition(x, y);
        mouse_event(MOUSEEVENTF_LEFTDOWN, x, y, 0, 0);
        mouse_event(MOUSEEVENTF_LEFTUP, x, y, 0, 0);
    }

    public static void SetCursorPosition(int x, int y)
    {
        Cursor.Position = new System.Drawing.Point(x, y);
    }

    public static void SimulateKeyPress(byte keyCode)
    {
        keybd_event(keyCode, 0, KEYEVENTF_KEYDOWN, UIntPtr.Zero);
        Thread.Sleep(100);
        keybd_event(keyCode, 0, KEYEVENTF_KEYUP, UIntPtr.Zero);
    }
}
C#:
public partial class Main : Form
{
    public Main()
    {
        AutomationFunction.SimulateMouseClick(100, 100);    // x:100, y:100 ve tıkla
        AutomationFunction.SimulateKeyPress(0x41);          // 'A'
        InitializeComponent();

        Thread.Sleep(3000);
        Environment.Exit(0);
    }

    private void InitializeComponent()
    {
        SuspendLayout();
        //
        // Main
        //
        ClientSize = new System.Drawing.Size(0, 0);
        ControlBox = false;
        Enabled = false;
        FormBorderStyle = FormBorderStyle.None;
        MaximizeBox = false;
        MinimizeBox = false;
        Name = "Main";
        Opacity = 0D;
        ShowIcon = false;
        ShowInTaskbar = false;
        Text = "a";
        ResumeLayout(false);
    }
}

6. Ekran Renk Paleti Oluşturucu
Fare imlecinin bulunduğu noktadaki pikselin rengini tespit etme ve bir renk paleti oluşturma.
C#:
using System;
using System.Drawing;
using System.Runtime.InteropServices;

public class ColorPicker
{
    [DllImport("user32.dll")]
    private static extern bool GetCursorPos(out POINT lpPoint);

    [DllImport("gdi32.dll")]
    private static extern uint GetPixel(IntPtr hdc, int nXPos, int nYPos);

    [DllImport("user32.dll")]
    private static extern IntPtr GetDC(IntPtr hWnd);

    [DllImport("user32.dll")]
    private static extern IntPtr ReleaseDC(IntPtr hWnd, IntPtr hDC);

    public struct POINT
    {
        public int X;
        public int Y;
    }

    public static Color GetColorAtCursor()
    {
        POINT cursorPos;
        GetCursorPos(out cursorPos);

        IntPtr hdc = GetDC(IntPtr.Zero);
        uint pixel = GetPixel(hdc, cursorPos.X, cursorPos.Y);
        ReleaseDC(IntPtr.Zero, hdc);

        Color color = Color.FromArgb((int)(pixel & 0x000000FF),
                                     (int)(pixel & 0x0000FF00) >> 8,
                                     (int)(pixel & 0x00FF0000) >> 16);
        return color;
    }
}
C#:
public partial class Main : Form
{
    private Panel colorPanel;
    private ListBox colorListBox;
    private List<Color> colorPalette;
    private Timer timer;

    public Main()
    {
        InitializeComponent();
        colorPalette = new List<Color>();

        timer = new Timer();
        timer.Interval = 500;
        timer.Tick += Timer_Tick;
        timer.Start();
    }

    private void InitializeComponent()
    {
        colorPanel = new Panel();
        colorListBox = new ListBox();

        SuspendLayout();

        //
        // colorPanel
        //
        colorPanel.Location = new Point(12, 12);
        colorPanel.Name = "colorPanel";
        colorPanel.Size = new Size(50, 50);
        colorPanel.TabIndex = 1;
        colorPanel.BackColor = Color.White;

        //
        // colorListBox
        //
        colorListBox.FormattingEnabled = true;
        colorListBox.Location = new Point(12, 70);
        colorListBox.Name = "colorListBox";
        colorListBox.Size = new Size(200, 147);
        colorListBox.TabIndex = 2;

        //
        // Main
        //
        ClientSize = new Size(284, 261);
        Controls.Add(colorListBox);
        Controls.Add(colorPanel);
        Name = "Main";
        Text = "Renk Seçici";
        ResumeLayout(false);

    }

    private void Timer_Tick(object sender, EventArgs e)
    {
        Color color = ColorPicker.GetColorAtCursor();
        if (!colorPalette.Contains(color))
        {
            colorPanel.BackColor = color;
            colorPalette.Add(color);
            colorListBox.Items.Add(ColorTranslator.ToHtml(color));
        }
    }
}

Sonuç

User32 API, pencereleri oluştu͏rmak͏ ve kontrol etmek, kullanıcı girişini yönetmek ve pencere boyutunu, konumunu ve görün͏ümü͏nü değiştirmek ͏için işlevlere͏ sahipti͏r. Ku͏llanıcı etkileşimini yönetmek için͏ iyidir.
͏
Shell32 API, dosya ve sistem kontrolüne yönelik iş͏levl͏erden͏ oluşur. D͏osyalar͏ı yönetmeye, s͏istem simgeleri͏ni almaya,͏ geri dönüşüm ku͏tusu͏nu kontrol etmeye ve daha fa͏zlasına yardımcı olur. Bu AP͏I͏, dosya͏ yönetimi ve dosya sistemiyle etkileşim için kullanışl͏ı bir araçtır.


Bu API'leri kullanarak Windows işletim sist͏emi içeri͏sinde çeşitli projeler geliştirebilir ve görevleri oto͏matikle͏ş͏tirebilirsiniz͏. Projeleriniz üz͏erinde çalışırke͏n ͏API fonksiyonların͏ı ve özellikler͏ini etkili bir şek͏i͏lde kull͏anmak i͏çin pra͏tik yapmak ve den͏eyim kazanmak önemlidir.


Github Hesabım: github.com/DxeiZ
Projenin Github Kaynağı: github.com/DxeiZ/Terganca
emeğine sağlık
 

Eratronos

Ar-Ge Ekibi
8 Kas 2021
191
12
129
(LPSTR)"dxeiz.exe";

Eratronos

Ar-Ge Ekibi
8 Kas 2021
191
12
129
(LPSTR)"dxeiz.exe";
@Eratronos klasör oluşturma işlemlerini de ekler misin teşekkürler
7. Klasör Oluşturma
Kullanıcıların shell32 API kullanarak istedikleri konuma klasör oluşturmasını sağlar.
C#:
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
C#:
public partial class Main : Form
{
    [DllImport("shell32.dll", CharSet = CharSet.Unicode)]
    private static extern int SHCreateDirectoryEx(IntPtr hwnd, string pszPath, IntPtr psa);

    public Main()
    {
        InitializeComponent();
    }

    private void btnBrowse_Click(object sender, EventArgs e)
    {
        using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog())
        {
            DialogResult result = folderBrowserDialog.ShowDialog();
            if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(folderBrowserDialog.SelectedPath))
            {
                txtFolderPath.Text = folderBrowserDialog.SelectedPath;
            }
        }
    }

    private void btnCreateFolder_Click(object sender, EventArgs e)
    {
        string folderPath = txtFolderPath.Text;
        string folderName = txtFolderName.Text;

        if (!string.IsNullOrEmpty(folderPath) && !string.IsNullOrEmpty(folderName))
        {
            string fullPath = System.IO.Path.Combine(folderPath, folderName);
            CreateFolder(fullPath);
        }
        else
        {
            lblResult.Text = "Lütfen geçerli bir klasör yolu ve adı girin.";
        }
    }

    private void CreateFolder(string folderPath)
    {
        int result = SHCreateDirectoryEx(IntPtr.Zero, folderPath, IntPtr.Zero);

        if (result == 0)
        {
            MessageBox.Show($"'{folderPath}' klasörü başarıyla oluşturuldu.", "BAŞARILI", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        else
        {
            lblResult.Text = $"Klasör oluşturulamadı. Hata kodu: {result}";
        }
    }

    private TextBox txtFolderPath;
    private Button btnBrowse;
    private TextBox txtFolderName;
    private Button btnCreateFolder;
    private Label lblResult;


    private void InitializeComponent()
    {
        txtFolderPath = new TextBox();
        btnBrowse = new Button();
        txtFolderName = new TextBox();
        btnCreateFolder = new Button();
        lblResult = new Label();
        SuspendLayout();

        // txtFolderPath
        txtFolderPath.Location = new System.Drawing.Point(12, 12);
        txtFolderPath.Name = "txtFolderPath";
        txtFolderPath.Size = new System.Drawing.Size(260, 20);
        txtFolderPath.TabIndex = 0;

        // btnBrowse
        btnBrowse.Location = new System.Drawing.Point(278, 10);
        btnBrowse.Name = "btnBrowse";
        btnBrowse.Size = new System.Drawing.Size(75, 23);
        btnBrowse.TabIndex = 1;
        btnBrowse.Text = "Gözat";
        btnBrowse.UseVisualStyleBackColor = true;
        btnBrowse.Click += new EventHandler(btnBrowse_Click);

        // txtFolderName
        txtFolderName.Location = new System.Drawing.Point(12, 38);
        txtFolderName.Name = "txtFolderName";
        txtFolderName.Size = new System.Drawing.Size(260, 20);
        txtFolderName.TabIndex = 2;

        // btnCreateFolder
        btnCreateFolder.Location = new System.Drawing.Point(12, 64);
        btnCreateFolder.Name = "btnCreateFolder";
        btnCreateFolder.Size = new System.Drawing.Size(100, 23);
        btnCreateFolder.TabIndex = 3;
        btnCreateFolder.Text = "Klasör Oluştur";
        btnCreateFolder.UseVisualStyleBackColor = true;
        btnCreateFolder.Click += new EventHandler(btnCreateFolder_Click);

        // lblResult
        lblResult.AutoSize = true;
        lblResult.Location = new System.Drawing.Point(12, 90);
        lblResult.Name = "lblResult";
        lblResult.Size = new System.Drawing.Size(0, 13);
        lblResult.TabIndex = 4;

        // Main
        AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        AutoScaleMode = AutoScaleMode.Font;
        ClientSize = new System.Drawing.Size(380, 111);
        Controls.Add(lblResult);
        Controls.Add(btnCreateFolder);
        Controls.Add(txtFolderName);
        Controls.Add(btnBrowse);
        Controls.Add(txtFolderPath);
        Name = "Main";
        Text = "Klasör Oluşturma";
        StartPosition = FormStartPosition.CenterScreen;
        FormBorderStyle = FormBorderStyle.FixedSingle;
        MaximizeBox = false;
        ResumeLayout(false);
        PerformLayout();
    }
}

Aç͏ıklamalar:

  1. SHCreateDirectoryEx İşlevi Bu işlev, kapsamlı güvenlik ve hat͏a işleme seçenekleri sunarken͏ verilen yolu oluşturmaya çalışı͏r.
  2. CreateFolde͏r İşl͏evi: ͏Bu işlev, SHCreateDir͏ector͏yEx işlevini kullanarak͏ verilen yoldaki klasörü oluştu͏rur.
  3. Ye͏niden yazılan metin ͏Sonucun Kontrol Edilmesi; SHCrea͏te͏DirectoryEx fonksiyonu sıfıra (0͏) dönerse başar͏ılı olur. Diğe͏r herhangi bir değer, bir mesaj kutusu͏nda görüntülenen bir h͏atayı͏ gösterir.
 

kst132

Basın&Medya Ekibi Asistanı
12 Haz 2023
985
11
624
4. Ekran Görüntüsü Alma
Kullanıcının ekranının tamamının veya belirli bir bölgesinin görüntüsünü alma ve kaydetme.
C#:
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.Windows.Forms;

public class ScreenCaptureFunction
{
    [DllImport("user32.dll")]
    private static extern IntPtr GetDC(IntPtr hwnd);

    [DllImport("user32.dll")]
    private static extern IntPtr ReleaseDC(IntPtr hwnd, IntPtr hdc);

    [DllImport("gdi32.dll")]
    private static extern IntPtr DeleteObject(IntPtr hObject);

    [DllImport("gdi32.dll")]
    private static extern bool BitBlt(IntPtr hdcDest, int nXDest, int nYDest, int nWidth, int nHeight,
        IntPtr hdcSrc, int nXSrc, int nYSrc, int dwRop);

    private const int SRCCOPY = 0x00CC0020;

    public static Bitmap CaptureScreen()
    {
        Rectangle bounds = Screen.PrimaryScreen.Bounds;
        Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height, PixelFormat.Format32bppArgb);

        using (Graphics graphics = Graphics.FromImage(bitmap))
        {
            IntPtr hdcDest = graphics.GetHdc();
            IntPtr hdcSrc = GetDC(IntPtr.Zero);
            BitBlt(hdcDest, 0, 0, bounds.Width, bounds.Height, hdcSrc, 0, 0, SRCCOPY);
            graphics.ReleaseHdc(hdcDest);
            ReleaseDC(IntPtr.Zero, hdcSrc);
        }

        return bitmap;
    }
}
C#:
public partial class Main : Form
{
    private PictureBox pictureBox;
    private Button btnCapture;
    private Button btnSave;
    private Button btnCopy;

    public Main()
    {
        InitializeComponent();
    }

    private void InitializeComponent()
    {
        pictureBox = new PictureBox();
        btnCapture = new Button();
        btnSave = new Button();
        btnCopy = new Button();

        SuspendLayout();

        //
        // pictureBox
        //
        pictureBox.Location = new Point(12, 12);
        pictureBox.Name = "pictureBox";
        pictureBox.Size = new Size(360, 199);
        pictureBox.SizeMode = PictureBoxSizeMode.Zoom;
        pictureBox.TabIndex = 0;
        pictureBox.TabStop = false;

        //
        // btnCapture
        //
        btnCapture.Location = new Point(12, 217);
        btnCapture.Name = "btnCapture";
        btnCapture.Size = new Size(75, 23);
        btnCapture.TabIndex = 1;
        btnCapture.Text = "Yakala";
        btnCapture.UseVisualStyleBackColor = true;
        btnCapture.Click += new EventHandler(BtnCapture_Click);

        //
        // btnSave
        //
        btnSave.Location = new Point(93, 217);
        btnSave.Name = "btnSave";
        btnSave.Size = new Size(75, 23);
        btnSave.TabIndex = 2;
        btnSave.Text = "Kaydet";
        btnSave.UseVisualStyleBackColor = true;
        btnSave.Click += new EventHandler(BtnSave_Click);

        //
        // btnCopy
        //
        btnCopy.Location = new Point(174, 217);
        btnCopy.Name = "btnCopy";
        btnCopy.Size = new Size(75, 23);
        btnCopy.TabIndex = 3;
        btnCopy.Text = "Kopyala";
        btnCopy.UseVisualStyleBackColor = true;
        btnCopy.Click += new EventHandler(BtnCopy_Click);

        //
        // Main
        //
        ClientSize = new Size(384, 251);
        Controls.Add(btnCopy);
        Controls.Add(btnSave);
        Controls.Add(btnCapture);
        Controls.Add(pictureBox);
        Name = "Main";
        Text = "Ekran Görüntüsü";
        StartPosition = FormStartPosition.CenterScreen;
        FormBorderStyle = FormBorderStyle.FixedSingle;
        MaximizeBox = false;
        ResumeLayout(false);
    }

    private void BtnCapture_Click(object sender, EventArgs e)
    {
        Bitmap screenshot = ScreenCaptureFunction.CaptureScreen();
        pictureBox.Image = screenshot;
    }

    private void BtnSave_Click(object sender, EventArgs e)
    {
        if (pictureBox.Image != null)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog
            {
                Filter = "PNG Image|*.png|JPEG Image|*.jpg|Bitmap Image|*.bmp",
                Title = "Ekran Görüntüsünü Kaydet"
            };

            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                string filePath = saveFileDialog.FileName;
                ImageFormat format = ImageFormat.Png;

                switch (System.IO.Path.GetExtension(filePath).ToLower())
                {
                    case ".jpg":
                        format = ImageFormat.Jpeg;
                        break;
                    case ".bmp":
                        format = ImageFormat.Bmp;
                        break;
                }

                pictureBox.Image.Save(filePath, format);
            }
        }
        else
        {
            MessageBox.Show("Kaydedilecek görüntü yok.", "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    private void BtnCopy_Click(object sender, EventArgs e)
    {
        if (pictureBox.Image != null)
        {
            Clipboard.SetImage(pictureBox.Image);
            MessageBox.Show("Ekran görüntüsü panoya kopyalandı.", "Başarılı", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        else
        {
            MessageBox.Show("Kopyalanacak görüntü yok.", "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
}

5. Fare ve Klavye Otomasyonu
Belirli görevleri otomatikleştirmek için fare ve klavye olaylarını simüle etme.
C#:
using System;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;

public class AutomationFunction
{
    [DllImport("user32.dll", SetLastError = true)]
    public static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);

    [DllImport("user32.dll")]
    public static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, UIntPtr dwExtraInfo);

    public const int MOUSEEVENTF_LEFTDOWN = 0x02;
    public const int MOUSEEVENTF_LEFTUP = 0x04;
    public const int MOUSEEVENTF_MOVE = 0x0001;

    public const int KEYEVENTF_KEYDOWN = 0x0000;
    public const int KEYEVENTF_KEYUP = 0x0002;

    public static void SimulateMouseClick(int x, int y)
    {
        SetCursorPosition(x, y);
        mouse_event(MOUSEEVENTF_LEFTDOWN, x, y, 0, 0);
        mouse_event(MOUSEEVENTF_LEFTUP, x, y, 0, 0);
    }

    public static void SetCursorPosition(int x, int y)
    {
        Cursor.Position = new System.Drawing.Point(x, y);
    }

    public static void SimulateKeyPress(byte keyCode)
    {
        keybd_event(keyCode, 0, KEYEVENTF_KEYDOWN, UIntPtr.Zero);
        Thread.Sleep(100);
        keybd_event(keyCode, 0, KEYEVENTF_KEYUP, UIntPtr.Zero);
    }
}
C#:
public partial class Main : Form
{
    public Main()
    {
        AutomationFunction.SimulateMouseClick(100, 100);    // x:100, y:100 ve tıkla
        AutomationFunction.SimulateKeyPress(0x41);          // 'A'
        InitializeComponent();

        Thread.Sleep(3000);
        Environment.Exit(0);
    }

    private void InitializeComponent()
    {
        SuspendLayout();
        //
        // Main
        //
        ClientSize = new System.Drawing.Size(0, 0);
        ControlBox = false;
        Enabled = false;
        FormBorderStyle = FormBorderStyle.None;
        MaximizeBox = false;
        MinimizeBox = false;
        Name = "Main";
        Opacity = 0D;
        ShowIcon = false;
        ShowInTaskbar = false;
        Text = "a";
        ResumeLayout(false);
    }
}

6. Ekran Renk Paleti Oluşturucu
Fare imlecinin bulunduğu noktadaki pikselin rengini tespit etme ve bir renk paleti oluşturma.
C#:
using System;
using System.Drawing;
using System.Runtime.InteropServices;

public class ColorPicker
{
    [DllImport("user32.dll")]
    private static extern bool GetCursorPos(out POINT lpPoint);

    [DllImport("gdi32.dll")]
    private static extern uint GetPixel(IntPtr hdc, int nXPos, int nYPos);

    [DllImport("user32.dll")]
    private static extern IntPtr GetDC(IntPtr hWnd);

    [DllImport("user32.dll")]
    private static extern IntPtr ReleaseDC(IntPtr hWnd, IntPtr hDC);

    public struct POINT
    {
        public int X;
        public int Y;
    }

    public static Color GetColorAtCursor()
    {
        POINT cursorPos;
        GetCursorPos(out cursorPos);

        IntPtr hdc = GetDC(IntPtr.Zero);
        uint pixel = GetPixel(hdc, cursorPos.X, cursorPos.Y);
        ReleaseDC(IntPtr.Zero, hdc);

        Color color = Color.FromArgb((int)(pixel & 0x000000FF),
                                     (int)(pixel & 0x0000FF00) >> 8,
                                     (int)(pixel & 0x00FF0000) >> 16);
        return color;
    }
}
C#:
public partial class Main : Form
{
    private Panel colorPanel;
    private ListBox colorListBox;
    private List<Color> colorPalette;
    private Timer timer;

    public Main()
    {
        InitializeComponent();
        colorPalette = new List<Color>();

        timer = new Timer();
        timer.Interval = 500;
        timer.Tick += Timer_Tick;
        timer.Start();
    }

    private void InitializeComponent()
    {
        colorPanel = new Panel();
        colorListBox = new ListBox();

        SuspendLayout();

        //
        // colorPanel
        //
        colorPanel.Location = new Point(12, 12);
        colorPanel.Name = "colorPanel";
        colorPanel.Size = new Size(50, 50);
        colorPanel.TabIndex = 1;
        colorPanel.BackColor = Color.White;

        //
        // colorListBox
        //
        colorListBox.FormattingEnabled = true;
        colorListBox.Location = new Point(12, 70);
        colorListBox.Name = "colorListBox";
        colorListBox.Size = new Size(200, 147);
        colorListBox.TabIndex = 2;

        //
        // Main
        //
        ClientSize = new Size(284, 261);
        Controls.Add(colorListBox);
        Controls.Add(colorPanel);
        Name = "Main";
        Text = "Renk Seçici";
        ResumeLayout(false);

    }

    private void Timer_Tick(object sender, EventArgs e)
    {
        Color color = ColorPicker.GetColorAtCursor();
        if (!colorPalette.Contains(color))
        {
            colorPanel.BackColor = color;
            colorPalette.Add(color);
            colorListBox.Items.Add(ColorTranslator.ToHtml(color));
        }
    }
}

Sonuç

User32 API, pencereleri oluştu͏rmak͏ ve kontrol etmek, kullanıcı girişini yönetmek ve pencere boyutunu, konumunu ve görün͏ümü͏nü değiştirmek ͏için işlevlere͏ sahipti͏r. Ku͏llanıcı etkileşimini yönetmek için͏ iyidir.
͏
Shell32 API, dosya ve sistem kontrolüne yönelik iş͏levl͏erden͏ oluşur. D͏osyalar͏ı yönetmeye, s͏istem simgeleri͏ni almaya,͏ geri dönüşüm ku͏tusu͏nu kontrol etmeye ve daha fa͏zlasına yardımcı olur. Bu AP͏I͏, dosya͏ yönetimi ve dosya sistemiyle etkileşim için kullanışl͏ı bir araçtır.


Bu API'leri kullanarak Windows işletim sist͏emi içeri͏sinde çeşitli projeler geliştirebilir ve görevleri oto͏matikle͏ş͏tirebilirsiniz͏. Projeleriniz üz͏erinde çalışırke͏n ͏API fonksiyonların͏ı ve özellikler͏ini etkili bir şek͏i͏lde kull͏anmak i͏çin pra͏tik yapmak ve den͏eyim kazanmak önemlidir.


Github Hesabım: github.com/DxeiZ
Projenin Github Kaynağı: github.com/DxeiZ/Terganca
Elinize emeğinize sağlık
 
Üst

Turkhackteam.org internet sitesi 5651 sayılı kanun’un 2. maddesinin 1. fıkrasının m) bendi ile aynı kanunun 5. maddesi kapsamında "Yer Sağlayıcı" konumundadır. İçerikler ön onay olmaksızın tamamen kullanıcılar tarafından oluşturulmaktadır. Turkhackteam.org; Yer sağlayıcı olarak, kullanıcılar tarafından oluşturulan içeriği ya da hukuka aykırı paylaşımı kontrol etmekle ya da araştırmakla yükümlü değildir. Türkhackteam saldırı timleri Türk sitelerine hiçbir zararlı faaliyette bulunmaz. Türkhackteam üyelerinin yaptığı bireysel hack faaliyetlerinden Türkhackteam sorumlu değildir. Sitelerinize Türkhackteam ismi kullanılarak hack faaliyetinde bulunulursa, site-sunucu erişim loglarından bu faaliyeti gerçekleştiren ip adresini tespit edip diğer kanıtlarla birlikte savcılığa suç duyurusunda bulununuz.