Shell32 ve User32 API'larıyla Güçlü Windows Sistem Araçları
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:
- Shell32 API: Dosya ve Sistem Yönetiminde İleri Düzey Çözümler
- 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);
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..