C# WPF

Képek kezelése
grid x:Name="LayoutRoot" UseLayoutRounding="True"

WPF Stílusok (WPF Styles)

Office 2010 gomb:

<!-- Office2010 ButtonStyle -->
 <style x:key="ShadowStyle">
        <Setter Property="Control.Foreground" Value="LightGray" />
 </style>
    <style x:key="Office2010Button" targettype="Button">
        <Setter Property="OverridesDefaultStyle" Value="True"/>
        <Setter Property="Margin" Value="2"/>
        <Setter Property="BorderBrush">
            <Setter.Value>
                <LinearGradientBrush StartPoint="0,0" EndPoint="0,1" >
                    <GradientStop Color="#FFDEDFE0" Offset="0"/>
                    <GradientStop Color="#FFA1A2A4" Offset="1"/>
                </LinearGradientBrush>
            </Setter.Value>
        </Setter>
        <Setter Property="Button.Effect">
         <Setter.Value>
           <DropShadowEffect Color="#A1000000" Direction="300" ShadowDepth="1" BlurRadius="3" Opacity="0.2" />
         </Setter.Value>
        </Setter>
        <Setter Property="Background" >
            <Setter.Value>
                <LinearGradientBrush StartPoint="0,0" EndPoint="0,1" >
                    <GradientStop Color="#FFFFFFFF" Offset="0"/>
                    <GradientStop Color="#FFEDEFF1" Offset="1"/>
                </LinearGradientBrush>
            </Setter.Value>
        </Setter>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <Border Name="border"
                        BorderThickness="1"
                        Padding="2"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        CornerRadius="2"
                        Background="{TemplateBinding Background}">
                        <Grid >
                            <ContentPresenter HorizontalAlignment="Center"
                                       VerticalAlignment="Center" Name="contentShadow"
                            Style="{StaticResource ShadowStyle}">
                                <ContentPresenter.RenderTransform>
                                    <TranslateTransform X="1.0" Y="1.0" />
                                </ContentPresenter.RenderTransform>
                            </ContentPresenter>
                            <ContentPresenter HorizontalAlignment="Center"
                                    VerticalAlignment="Center" Name="content"/>
                        </Grid>
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter TargetName="border" Property="BorderBrush" Value="#FFF0C857" />
                            <Setter Property="Background" >
                                <Setter.Value>
                                    <LinearGradientBrush StartPoint="0,0" EndPoint="0,1" >
                                        <GradientStop Color="#FFFCF0BC" Offset="0"/>
                                        <GradientStop Color="#FFFCE285" Offset="0.50"/>
                                        <GradientStop Color="#FFFDF8C8" Offset="1"/>
                                    </LinearGradientBrush>
                                </Setter.Value>
                            </Setter>
                        </Trigger>
                        <Trigger Property="IsPressed" Value="True">
                            <Setter TargetName="border" Property="BorderBrush" Value="#FFC28A30" />
                            <Setter Property="Background" >
                                <Setter.Value>
                                    <LinearGradientBrush StartPoint="0,0" EndPoint="0,1" >
                                        <GradientStop Color="#FFFFE575" Offset="0"/>
                                        <GradientStop Color="#FFFFD86B" Offset="0.50"/>
                                        <GradientStop Color="#FFFFEF81" Offset="1"/>
                                    </LinearGradientBrush>
                                </Setter.Value>
                            </Setter>
                            <Setter TargetName="content" Property="RenderTransform" >
                                <Setter.Value>
                                    <TranslateTransform Y="1.0" />
                                </Setter.Value>
                            </Setter>
                        </Trigger>
                        <Trigger Property="IsDefaulted" Value="True">
                            <Setter TargetName="border" Property="BorderBrush" Value="#FF0094FF" />
                        </Trigger>
                        <Trigger Property="IsFocused" Value="True"></Trigger>
                        <Trigger Property="IsEnabled" Value="False">
                            <Setter TargetName="border" Property="Opacity" Value="0.7" />
                            <Setter Property="Foreground" Value="Gray" />
                        </Trigger>
 
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </style>

Vista / Win7 parancsgomb:

<!-- Vista style Command Button -->
<style x:key="ShadowStyle">
        <Setter Property="Control.Foreground" Value="LightGray" />
    </style>
    <style x:key="VistaCommandButton" targettype="Button">
        <Setter Property="OverridesDefaultStyle" Value="True"/>
        <Setter Property="Margin" Value="2"/>
        <Setter Property="Button.Effect">
         <Setter.Value>
    <DropShadowEffect Color="#A1000000" Direction="300" ShadowDepth="1" BlurRadius="3" Opacity="0.2" />
         </Setter.Value>
        </Setter>
        <Setter Property="Background" Value="Transparent"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <Border Name="border"
                        BorderThickness="1"
                        Padding="2"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        CornerRadius="2"
                        Background="{TemplateBinding Background}">
                        <Grid >
                            <ContentPresenter HorizontalAlignment="Center"
                                       VerticalAlignment="Center" Name="contentShadow"
                            Style="{StaticResource ShadowStyle}">
                                <ContentPresenter.RenderTransform>
                                    <TranslateTransform X="1.0" Y="1.0" />
                                </ContentPresenter.RenderTransform>
                            </ContentPresenter>
                            <ContentPresenter HorizontalAlignment="Center"
                                    VerticalAlignment="Center" Name="content"/>
                        </Grid>
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter TargetName="border" Property="BorderBrush" Value="#4E000000" />
                            <Setter Property="Background" >
                                <Setter.Value>
                                    <LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
                                        <GradientStop Color="#78FAFAFA" Offset="0.0"/>
                                        <GradientStop Color="#31C5C5C5" Offset="0.30" />
                                        <GradientStop Color="#286D6D6D" Offset="0.30" />
                                        <GradientStop Color="#28727272" Offset="0.45" />
                                        <GradientStop Color="#12F0F0F0" Offset="1.0" />
                                    </LinearGradientBrush>
                                </Setter.Value>
                            </Setter>
                        </Trigger>
                        <Trigger Property="IsPressed" Value="True">
                            <Setter TargetName="border" Property="BorderBrush" Value="#7C000000" />
                            <Setter Property="Background" >
                                <Setter.Value>
                                    <LinearGradientBrush StartPoint="0,0" EndPoint="0,1" >
                                        <GradientStop Color="#53313131" Offset="0.02" />
                                        <GradientStop Color="#1B000000" Offset="0.06" />
                                        <GradientStop Color="#0D000000" Offset="0.45" />
                                        <GradientStop Color="#0B000000" Offset="1.0" />
                                    </LinearGradientBrush>
                                </Setter.Value>
                            </Setter>
                            <Setter TargetName="content" Property="RenderTransform" >
                                <Setter.Value>
                                    <TranslateTransform Y="1.0" />
                                </Setter.Value>
                            </Setter>
                        </Trigger>
                        <Trigger Property="IsDefaulted" Value="True">
                            <Setter TargetName="border" Property="BorderBrush" Value="#4E000000" />
                        </Trigger>
                        <Trigger Property="IsFocused" Value="True"></Trigger>
                        <Trigger Property="IsEnabled" Value="False">
                            <Setter TargetName="border" Property="Opacity" Value="0.7" />
                            <Setter Property="Foreground" Value="Gray" />
                        </Trigger>
 
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </style>

Program Futtatása

System.Diagnostics.Process.Start("c:\\Windows\\regedit.exe");

Ha a fájl nem található (védelem)…

const int ERROR_FILE_NOT_FOUND = 2;
try
{
  System.Diagnostics.Process.Start("c:\\myapp.exe");
}
catch (Win32Exception h)
{
  if (h.NativeErrorCode == ERROR_FILE_NOT_FOUND)
  {
  MessageBox.Show("c:\\myapp.exe", "A Fájl Nem Található!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  }
}

Folyamat leállítása

Process[] prs = Process.GetProcesses();
foreach (Process pr in prs)
{
if (pr.ProcessName == "ffmpeg")//Folyamat neve...
  {
    pr.Kill();
    MessageBox.Show("Folyamat leállítva!", "Figyelem", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  }
}

Registry Írás

//String:
Microsoft.Win32.RegistryKey key;
key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey("Names");
key.SetValue("Name", "Isabella");
key.Close();
//Dword:
Microsoft.Win32.RegistryKey key;
key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey("SOFTWARE\\techPowerUp\\GPU-Z");
key.SetValue("Interval", 0x00003);
key.Close();

Registry Törlés

string keyName = @"Software\Microsoft\Windows\CurrentVersion\Run";
using (RegistryKey key = Registry.CurrentUser.OpenSubKey(keyName, true))
{
    if (key == null)
    {
        // Key doesn't exist. Do whatever you want to handle
        // this case
    }
    else
    {
        key.DeleteValue("MyApp");
    }
}
//Vagy egész kulcs
RegistryKey registrykeyHKLM = Registry.LocalMachine;
string keyPath = @"Software\Microsoft\Windows\CurrentVersion\Run\MyApp";
registrykeyHKLM.DeleteValue(keyPath);
registrykeyHKLM.Close();

string-ről int-re és int-ről string-re

//string to int
int x = Int.Parse("23");
//int to string
int var1 = 2;
string var2 = var1.ToString;

Sortörés és macskaköröm

//Sortörés
\n
//Macskaköröm
"\""

Elérési útvonalak

//Temp mappa
string temp = Path.GetTempPath();
//Windows mappa
string windir = Environment.GetEnvironmentVariable("WINDIR");
//Program Files mappa
string programfiles = Environment.GetEnvironmentVariable("PROGRAMFILES");
//Felhasználói könyvtár
string users = Environment.GetEnvironmentVariable("USERPROFILE");
//Asztal
string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
//Program gyökérmappája
string rootpath = Path.GetDirectoryName(Application.ExecutablePath);

Átlátszó lapos gomb (kép is elhelyezhető)

button1.TabStop = false;
button1.FlatStyle = FlatStyle.Flat;
button1.FlatAppearance.BorderSize = 0;
button1.FlatAppearance.BorderColor = Color.FromArgb(0, 255, 255, 255); //Transparent

Ablak (form) Bezárása

Close();

Másolandó Fájl nem létezik akkor…

FileInfo updatefiles = new FileInfo("C:\\Zipp\\akarmi.zip");
if (File.Exists("updatefiles.ToString()))
  {
    updatefiles.CopyTo("C:\\File\\akarmi.zip", true);
  }
else
 {
    MessageBox.Show("C:\\Zipp\\akarmi.zip Nem Található!");
 }

Szöveges Fájl Létrehozása

using (StreamWriter sw = new StreamWriter("TestFile.txt"))
{
// Add some text to the file.
sw.Write("This is the ");
sw.WriteLine("header for the file.");
sw.WriteLine("-------------------");
// Arbitrary objects can also be written to the file.
sw.Write("The date is: ");
sw.WriteLine(DateTime.Now);
sw.Close();
}

Asztal Frissítése

[System.Runtime.InteropServices.DllImport("Shell32.dll")]
private static extern int SHChangeNotify(int eventId, int flags, IntPtr item1, IntPtr item2);
 private void button1_Click(object sender, EventArgs e)
        {
            SHChangeNotify(0x8000000, 0x1000, IntPtr.Zero, IntPtr.Zero);
        }

Kép konvertálása

using System.Drawing.Imaging;
 
using(Image img = Image.FromFile("c:\\jpegimage.jpg"))
   {
    img.Save("C:\\bmpimage.bmp", ImageFormat.Bmp);
    //PNG mentés:
    img.Save(@"C:\newfile.png", ImageFormat.Png);
   }

Egyszerű nyomtatás

//elhelyezkedések//
float x = 75.0F;
float y = 510.0F;
private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
        {
            Font drawFont = textBox1.Font;
            SolidBrush drawBrush = new SolidBrush(textBox1.ForeColor);
            e.Graphics.DrawString(textBox1.Text, drawFont, drawBrush, x, y);
        }
private void button3_Click(object sender, EventArgs e)
        {
            DialogResult result = printDialog1.ShowDialog();
            // If the result is OK then print the document.
            if (result == DialogResult.OK)
            {
                printDocument1.Print();
            }  
        }

Parancsikon készítése

using IWshRuntimeLibrary;
 
string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);//Asztal
WshShell = new WshShellClass();
IWshRuntimeLibrary.IWshShortcut MyShortcut;
// Helye a para ikonak "Hova kerüljön"
MyShortcut = (IWshRuntimeLibrary.IWshShortcut)WshShell.CreateShortcut(desktop + @"\Aero Shot.lnk");
// Ahol a program található
MyShortcut.TargetPath = path;
// Parancsikon leírása
MyShortcut.Description = "Képmetsző progi.";
// Ikon helye
MyShortcut.IconLocation = path;
// Parancsikon Mentése
MyShortcut.Save();

2. Ablak megjelenítése

Form2 frmK = new Form2();//A Form2 a második form neve (változtatható)
frmK.ShowDialog();

Meglévő XML fájl adatához hozzáadás

using System.Xml;
using System.Xml.Linq;
//XML létrehozása és a gyökér elem létrehozása
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.IndentChars = ("\t");
settings.OmitXmlDeclaration = false;
settings.Encoding = Encoding.UTF8;
XmlWriter writer = XmlWriter.Create("logs.xml",settings);
writer.WriteStartDocument();
writer.WriteStartElement("Log");
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Close();
//XML létrehozás vége....
//Gyökér elemen belüli elemek létrehozása
DateTime dt = DateTime.Now;
string date = dt.ToShortDateString();
string time = dt.ToLongTimeString();
XDocument doc = XDocument.Load("logs.xml");
XElement root = new XElement("Messenge");
root.Add(new XAttribute("Date", date));
root.Add(new XAttribute("Time", time));
XElement userfrom = new XElement("User", "Valaki");
XElement userto = new XElement("User", "Tommy");
root.Add(new XElement("From", userfrom));
root.Add(new XElement("To", userto));
root.Add(new XElement("Text", "Messenges!"));
//Itt a gyökér nevét kell megadni
doc.Element("Log").Add(root);
doc.Save("logs.xml");

Datagridview sor szinezése

int RowIndex = 5;
this.dataGridView1.Rows[RowIndex].DefaultCellStyle.BackColor = Color.FromArgb(123,225,0);

ColorDialog szín elmentése hexakódban

Color color;
color = colorDialog1.Color;
string htmlColor = ColorTranslator.ToHtml(color);

Hexa színkód vagy html színkód megadása textbox színének

string Font_color = "#FF8000";
colors = (Color)ColorTranslator.FromHtml(Font_color);
textBox1.ForeColor = colors;

Folyamat (vagy program) felfüggesztése név alapján

[DllImport("kernel32.dll")]
        static extern IntPtr OpenThread(ThreadAccess dwDesiredAccess, bool bInheritHandle, uint dwThreadId);
        [DllImport("kernel32.dll")]
        static extern uint SuspendThread(IntPtr hThread);
        [DllImport("kernel32.dll")]
        static extern int ResumeThread(IntPtr hThread);
 
        [DllImport("Kernel32")]
        private extern static Boolean CloseHandle(IntPtr handle);
 
        private static void SuspendProcess(int pid)
        {
            var process = Process.GetProcessById(pid);
 
            if (process.ProcessName == string.Empty)
                return;
 
            foreach (ProcessThread pT in process.Threads)
            {
                IntPtr pOpenThread = OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint)pT.Id);
 
                if (pOpenThread == IntPtr.Zero)
                {
                    continue;
                }
 
                SuspendThread(pOpenThread);
 
                CloseHandle(pOpenThread);
            }
        }
 
        public static void ResumeProcess(int pid)
        {
            var process = Process.GetProcessById(pid);
 
            if (process.ProcessName == string.Empty)
                return;
 
            foreach (ProcessThread pT in process.Threads)
            {
                IntPtr pOpenThread = OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint)pT.Id);
 
                if (pOpenThread == IntPtr.Zero)
                {
                    continue;
                }
 
                var suspendCount = 0;
                do
                {
                    suspendCount = ResumeThread(pOpenThread);
                } while (suspendCount > 0);
 
                CloseHandle(pOpenThread);
            }
        }
        //Felfüggesztő esemény pl.: Button
        private void button1_Click(object sender, EventArgs e)
        {
        //itt adjuk meg a program vagy folyamat nevét
            Process[] p = Process.GetProcessesByName("sajatprogram");
            foreach (var proc in p)
            pid = proc.Id;
            if (button1.Text == "Pause")
            {
                button1.Text = "Resume";
                SuspendProcess(pid);
            }
            else if (button1.Text == "Resume")
            {
                button1.Text = "Pause";
                ResumeProcess(pid);
            }
        }

Direkt Eseménykezelés

try{
ValamiEsemeny(null, EventArgs.Empty);
}
 
private void ValamiEsemeny(object sender, EventArgs e)
        {
            CheckBox6_CheckChanged(sender, e);
            //Eseményt előidéző szöveg/érték/tulajdonság megjelenítése:
            Button foo = sender as Button;
            string s = foo.Text;
        }

INI fájl létrehozása/olvasása
A szükséges fájl illetve a projekt letölthető itt: INI file handling class using C#

using INI;
//ini fájl létrehozása
INIFile ini = new INIFile("C:\\test.ini");
//ini fájl olvasása
if (ini.IniReadValue("Settings", "Preset") == "true")
        {
            Bla bla....
        }
//ini fájl írása
ini.IniWriteValue("Settings", "Preset", "false");

A ListView Win7/Vista rendszertéma (stílus) alkalmazása

using System.Runtime.InteropServices;
 
    public const int LVM_FIRST = 0x1000;
    public const int LVM_SETEXTENDEDLISTVIEWSTYLE = LVM_FIRST + 54;
    public const int LVS_EX_DOUBLEBUFFER = 0x00010000;
    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    public static extern IntPtr SendMessage(IntPtr hWnd, int msg, int wParam, int lParam);
    //Imports the UXTheme DLL
    [DllImport("uxtheme", CharSet = CharSet.Unicode)]
    public extern static Int32 SetWindowTheme(IntPtr hWnd, String textSubAppName, String textSubIdList);
         
public Form1()
{
   InitializeComponent();
   SetWindowTheme(listView1.Handle, "explorer", null); //Explorer style
   SendMessage(listView1.Handle, LVM_SETEXTENDEDLISTVIEWSTYLE, LVS_EX_DOUBLEBUFFER, LVS_EX_DOUBLEBUFFER);
}

ListView kiválasztott elem index megjelenítése

int selectindex = listView1.FocusedItem.Index;

Egy karakter előtt és utána lévő szöveg megjelenítése

string xy = "1891x1234";
string elso = xy.Substring(0,xy.IndexOf('x'));
string utolso = xy.Substring(xy.IndexOf('x') + 1);
//output: elso=1891 utolso=1234

TextBox Nagybetű

textBox1.CharacterCasing = CharacterCasing.Upper;

Program futtatása rendszergazdaként:

Process proc = new Process();
    proc.StartInfo.FileName = fileName;
    proc.StartInfo.UseShellExecute = true;
    proc.StartInfo.Verb = "runas";
    proc.Start();