[DllImport("user32.dll")]
public static extern void LockWorkStation()
// Lock workstation
LockWorkStation();
[DllImport("user32.dll")]
public static extern void LockWorkStation()
// Lock workstation
LockWorkStation();
با سلام
این هم از اولین نکته من
امیدوارم که تکراری نباشه
لیست برنامه ها نصب شده در مسیر زیر درون رجیستری قرار میگیره:
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\Curr entVersion\Uninstall
خب حالا برای بدست آوردنشون:
private void GetInstalledPrograms()
{
RegistryKey localmachine = Registry.LocalMachine;
RegistryKey uninstall = localmachine.OpenSubKey(@"Software\Microsoft\Windo ws\CurrentVersion\Uninstall");
foreach (string key in uninstall.GetSubKeyNames())
{
RegistryKey activeKey = uninstall.OpenSubKey(key);
string displayName = (string)activeKey.GetValue("DisplayName");
if (!String.IsNullOrEmpty(displayName))
listBox1.Items.Add(displayName);
}
}
موفق باشین![]()
آخرین ویرایش به وسیله Mahmoud.Afrad : چهارشنبه 27 خرداد 1394 در 02:43 صبح
ایجاد شفافیت کامل پشت زمینه ی یک کنترل :
control.BackColor = Color.Transparent;تعیین میزان شفافیت یک کنترل:
control.BackColor = Color.FromArgb(trancparency, control.BackColor);در کد بالا مقدار trancparency از 0 (برای کاملا شفاف) تا 255 (کاملا کدر) قابل تغییر است.
مثال : یک Label با شفافیت 50%
label1.BackColor = Color.FromArgb(127, label1.BackColor);
[DllImport("user32.dll")]
public static extern int ExitWindowsEx(int uFlags, int dwReason);
// Log Off
ExitWindowsEx(0, 0);
// Reboot
ExitWindowsEx(2, 0);
// Shutdown
ExitWindowsEx(1, 0);
// Force LogOff
ExitWindowsEx(4, 0);
و یا:
// Log Off
System.Diagnostics.Process.Start("ShutDown", "/l");
// Reboot
System.Diagnostics.Process.Start("ShutDown", "/r");
// Shutdown
System.Diagnostics.Process.Start("ShutDown", "/s");
مثال : بستن notepad
using System.Diagnostics;و یا :
foreach (Process p in Process.GetProcesses())
{
if (p.ProcessName.ToLower() == "notepad")
p.Kill();
}
System.Diagnostics.Process.Start("TaskKill", "/f /im Notepad.exe /t");
using System.Net.NetworkInformation;private void button2_Click(object sender, EventArgs e)منبع : http://www.dotnetspider.com/code/C-245-Ping-remote-computer-network.aspx
{
string remoteMachineNameOrIP = "127.0.0.1";
int timeOut = 5;
Ping ping = new Ping();
// Pinging remote maching
PingReply reply = ping.Send(remoteMachineNameOrIP, timeOut);
// Displaying the result
StringBuilder sb = new StringBuilder();
sb.Append("Address:" + reply.Address.ToString());
sb.Append("\nStatus:" + reply.Status.ToString());
sb.Append("\nRoundtripTime:" + reply.RoundtripTime.ToString());
MessageBox.Show(sb.ToString(), "Ping Result: " + remoteMachineNameOrIP);
}
MessageBox.Show(AppDomain.CurrentDomain.BaseDirect ory);یا :
MessageBox.Show(System.IO.Directory.GetCurrentDire ctory());یا :
MessageBox.Show(Application.StartupPath);یا:
MessageBox.Show(System.IO.Path.GetDirectoryName(Ap plication.ExecutablePath));
مثال : برگرداندن 10 رکورد تصادفی از جدول myTable
SELECT TOP 10 id,title
FROM myTable
ORDER BY NEWID()
کاربرد : زمانی که نمیتوان از یک الگوریتم بازگشتی استفاده کرد؛ برای مثال کنترلها در Container های متفاوتی هستند و تنها تعداد خاصی از آنها باید Clear شوند.
public void ClearControls(params Control[] ctls)
{
foreach (Control ct in ctls)
ct.Text = "";
}
private void button1_Click(object sender, EventArgs e)
{
ClearControls(textBox1, textBox2, comboBox1);
}
استفاده از کرسرهای پیشفرض محیط :
button1.Cursor = Cursors.Hand;
لود کردن یک کرسر سفارشی از فایل :
button1.Cursor = new Cursor(@"C:\WINDOWS\Cursors\hibeam.cur");
public void ClearControls(Control _parent)
{
if (!_parent.HasChildren)
_parent.Text = "";
foreach (Control ct in _parent.Controls)
ClearControls(ct);
}
private void button1_Click(object sender, EventArgs e)
{
ClearControls(this);
}
INSERT INTO Sales.Customer ([TerritoryID],[CustomerType]) VALUES (8,'S')
GO
SELECT SCOPE_IDENTITY()
برای اینکه خیلی سریع یک Property ایجاد کنی کافیه که کلمه prop رو تایپ کنین و دوباره Tab بزنین. بعد نوع داده ای , نام متغییر private و در نهایت نام Propety مورد نظرتون. با تایپ کردن 5 کلمه Property تون آمادست.
وقتی نام کلاسی رو می نویسین و می دونین که باید ازش using کنین کافیه که بعد تایپ کردن اسمش Alt + Shift + F10 و بعد Enter رو بزنین خودش براتون using رو اضافه می کنه!
برای خواندن ConnectionString ی که در فایل app.config قرار داده شده کافیه و ایجاد یک SqlConnection کافیه کد زیر را تایپ کنین:
SqlConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrin gs["myConnection"].ConnectionString);
برای Encrypt کردن قسمت ConnectionStrings فایل web.config یا app.Config از کد زیر استفاده می کنیم:
App.Config
Configuration config = ConfigurationManager.OpenExeConfiguration(Configur ationUserLevel.None);
config.ConnectionStrings.SectionInformation.ForceS ave = true;
config.ConnectionStrings.SectionInformation.Protec tSection("RsaProtectedConfigurationProvider");
config.Save();
Web.Config
Configuration config = WebConfigurationManager.OpenWebConfiguration("myWe bSite");
config.ConnectionStrings.SectionInformation.ForceS ave = true;
config.ConnectionStrings.SectionInformation.Protec tSection("RsaProtectedConfigurationProvider");
config.Save();
برای Decrypt کردن محتویات ConnectionString داخل فایل های Config از کد های زیر استفاده می کنیم:
برای App.Config
برای Web.Config
Configuration config = ConfigurationManager.OpenExeConfiguration(Configur ationUserLevel.None);
config.ConnectionStrings.SectionInformation.ForceS ave = true;
config.ConnectionStrings.SectionInformation.Unprot ectSection();
config.Save();
Configuration config = WebConfigurationManager.OpenWebConfiguration("myWe bSite");
config.ConnectionStrings.SectionInformation.ForceS ave = true;
config.ConnectionStrings.SectionInformation.Unprot ectSection();
config.Save();
آشنایی با Snippet ها باعث سرعت شما در محیط کدنویسی میشود. برای استفاده کافیست بلافاصله بعد از نوشتن آنها (و بدون ایجاد فاصله) دوبار دکمه Tab را فشار دهید. (توضیحات بیشتر)
در ادامه با چند اسنیپت متداول آشنا خواهید شد :
ایجاد یک ناحیه :#regionایجاد MessageBox :
mboxایجاد Constructor برای کلاس :
ctorایجاد متود Main :
svmبرای ایجاد کلاسها، ایندکسر، استراکچر، ...class, enum, struct, indexerبرای ایجاد انواع حلقه ها :forایجاد پراپرتی :
forr
foreach
while
dopropدستورات شرطی :
propgifو ...
else
switch
روش دیگر افزودن : روی یک قسمت خالی در محیط کدنویسی Right Click و سپس گزینه Insert Snippet رو انتخاب نمایید.
چنانچه کدی (مثلا 10 خط) نوشتید که میخواهید درون یک بلاک (حلقه، شرط و ...) قرار بگیره تمامی خطوط آن را Select و پس از Right Click گزینه Surround with رو انتخاب نمایید.
در لینک زیر نیز ضمن آشنایی با سایر موارد میتوانید snippet های مفید دیگری را نیز دانلود و به IDE خود بیفزایید.
لیست کامل سایر snippetها : http://msdn2.microsoft.com/en-us/vs2005/aa718338.aspx
ایجاد یک فرم دایره ای شکل :
private void Form1_Load(object sender, EventArgs e)منبع : http://www.dotnetspider.com/code/C-144-Create-Circle-shaped-Form-using-Regions.aspx
{
this.Height = 350;
this.Width = 350;
//Creating circle path
System.Drawing.Drawing2D.GraphicsPath path = new System.Drawing.Drawing2D.GraphicsPath();
path.AddEllipse(0, 0, 300, 300);
//Creating the region from the circle path
this.Region = new Region(path);
this.Show();
}
System.Diagnostics.Process.Start("rasdial", "/disconnect");
public struct LanguageHelper
{
public static void SetLanguage2English()
{
InputLanguage.CurrentInputLanguage = InputLanguage.FromCulture(new CultureInfo("en-US"));
}
public static void SetLanguage2Farsi()
{
InputLanguage.CurrentInputLanguage = InputLanguage.FromCulture(new CultureInfo("fa-IR"));
}
}
using System.Drawing.Drawing2D;حال این متود رو در رخداد Paint کنترلهای دلخواه (فرم، دکمه، پنل ...) بنویسید :
using System.Drawing;
public void PaintGradient(Control _control, LinearGradientMode _direction, Color _gradientColorStart, Color _gradientColorEnd)
{
LinearGradientBrush gradBrush;
gradBrush = new LinearGradientBrush(new Rectangle(0, 0, _control.Width, _control.Height), _gradientColorStart, _gradientColorEnd, _direction);
Bitmap bmp = new Bitmap(_control.Width, _control.Height);
Graphics g = Graphics.FromImage(bmp);
g.FillRectangle(gradBrush, new Rectangle(0, 0, _control.Width, _control.Height));
_control.BackgroundImage = bmp;
_control.BackgroundImageLayout = ImageLayout.Stretch;
}
private void Form1_Paint(object sender, PaintEventArgs e)خصوصا ظاهر بهتر و مناسبتری برای دکمه های شما ایجاد میکند.
{
PaintGradient(this, LinearGradientMode.Vertical, Color.RoyalBlue, Color.DarkBlue);
}
با استفاده از پیاده سازی ژنریک الگوی سینگلتون :
public class SingletonProvider<T> where T : new()و برای استفاده :
{
SingletonProvider() { }
public static T Instance
{
get
{
return SingletonCreator.Instance;
}
}
class SingletonCreator
{
static SingletonCreator(){}
private static T instance;
public static T Instance
{
get
{
System.Windows.Forms.Form frm = instance as System.Windows.Forms.Form;
if (instance == null || frm.IsDisposed==true)
instance = new T();
return instance;
}
}
}
}BoatForm boat = SingletonProvider<BoatForm>.Instance;
آموزش کامل این روش : https://barnamenevis.org/showthread.php?t=90581
گاهی بد نیست برای تنوع هم که شده ظاهر محیط کدنویسی رو از حالت یکنواخت و سفید همیشگی تغییر بدیم.
اینکار رو میتونید خودتون بسادگی انجام بدید و راحتتر از اون اینکه فایل تنظیمات رو از سایر سایتها (مانند سایت زیر ) دانلود و استفاده کنید:
http://idehotornot.ning.com
پس از دانلود فایل مورد نظر، جهت اعمال تغییرات در ویژوال استادیو مراحل زیر رو طی کنید :
Tools(menu)->Import and Export settings->Import...
برای مثال :string path = Environment.GetFolderPath(Environment.SpecialFolde r.ProgramFiles);سایر مسیرها قابل دستیابی با این روش :
Desktop, MyDocuments, System, ...بنقل از : https://barnamenevis.org/showpost.php?p=468371&postcount=3
using System.Runtime.InteropServices;
[DllImport("user32.dll")]
static extern int ReleaseCapture();
[DllImport("user32.dll", EntryPoint = "SendMessageA")]
static extern int SendMessage(int hwnd, int wMsg, int wParam, object lParam);
private const int WM_NCLBUTTONDOWN = 161;
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
ReleaseCapture();
SendMessage(this.Handle.ToInt32(), WM_NCLBUTTONDOWN, 2, 0);
}
public enum Days { Sat = 1, Sun, Mon, Tue, Wed, Thu, Fri };
string s= Enum.GetName(typeof(Days),4);
آخرین ویرایش به وسیله Mahmoud.Afrad : چهارشنبه 17 تیر 1394 در 12:52 عصر
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string[] colorNames;
colorNames = System.Enum.GetNames(typeof(KnownColor));
listBox1.Items.AddRange(colorNames);
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
KnownColor selectedColor;
selectedColor = (KnownColor)System.Enum.Parse(typeof(KnownColor), listBox1.Text);
this.BackColor = System.Drawing.Color.FromKnownColor(selectedColor) ;
}
}
منبع:pro.net2.0 windows forms and custom controls Apress
آخرین ویرایش به وسیله az_farzaneh : دوشنبه 26 فروردین 1387 در 11:41 صبح
public static int[] RandomNumbers(int n,int min,int max)
{
Random rnum = new Random();
HashSet<int> hset = new HashSet<int>();
while (hset.Count < n)
hset.Add(rnum.Next(min,max));
int[] OutPut = hset.ToArray();
return OutPut;
}
آخرین ویرایش به وسیله Mahmoud.Afrad : یک شنبه 20 خرداد 1397 در 09:03 صبح
با سلام کسی dll های نرم افزار حضور و غیاب رو داره یا میتونه راهنمایی کنه از کجا میتونم تهیه کنم
ابتدا System.Management رو به References پروژه بیفزایید و سپس :
using System.Management;
private void GetHDDSerialNumber()
{
ManagementObjectSearcher searcher;
string query1 = "SELECT * FROM Win32_DiskDrive";
string query2 = "SELECT * FROM Win32_PhysicalMedia";
searcher = new ManagementObjectSearcher(query1);
foreach (ManagementObject wmi_HD in searcher.Get())
if (wmi_HD["Model"] != null)
MessageBox.Show(wmi_HD["Model"].ToString());
searcher = new ManagementObjectSearcher(query2);
foreach (ManagementObject wmi_HD in searcher.Get())
if (wmi_HD["SerialNumber"] != null)
MessageBox.Show(wmi_HD["SerialNumber"].ToString());
}
int n = Convert.ToInt32(textBox1.Text);یا :
int n = Int32.Parse(textBox1.Text);و چنانچه امکان خطا باشد که تقریبا همیشه هست :
int n;در این حالت خروجی به n تخصیص داده میشود و چنانچه مشکلی رخ دهد n برابر صفر میشود.
Int32.TryParse(textBox1.Text, out n);
System.Diagnostics.Process.Start("mspaint.exe");
چنانچه فایل اجرایی نیاز به آرگومان خط فرمان داشته باشد :
System.Diagnostics.Process.Start("mspaint.exe", "c:\\Test.bmp");
مثال بالا تصویر Test را در msPaint باز میکند.
string myString1 = "This is the first line of my string.\n" +یا :
"This is the second line of my string.\n" +
"This is the third line of the string.\n";
string myString2 = @"This is the first line of my string.
This is the second line of my string.
This is the third line of the string.";
// Single-dimensional array (numbers).
int[] n1 = new int[4] {2, 4, 6, 8};
int[] n2 = new int[] {2, 4, 6, 8};
int[] n3 = {2, 4, 6, 8};// Single-dimensional array (strings).
string[] s1 = new string[3] {"John", "Paul", "Mary"};
string[] s2 = new string[] {"John", "Paul", "Mary"};
string[] s3 = {"John", "Paul", "Mary"};// Multidimensional array.
int[,] n4 = new int[3, 2] { {1, 2}, {3, 4}, {5, 6} };
int[,] n5 = new int[,] { {1, 2}, {3, 4}, {5, 6} };
int[,] n6 = { {1, 2}, {3, 4}, {5, 6} };// Jagged array.
int[][] n7 = new int[2][] { new int[] {2,4,6}, new int[] {1,3,5,7,9} };
int[][] n8 = new int[][] { new int[] {2,4,6}, new int[] {1,3,5,7,9} };
int[][] n9 = { new int[] {2,4,6}, new int[] {1,3,5,7,9} };
private Image CreateBitmap()
{
System.Drawing.Bitmap flag = new System.Drawing.Bitmap(10, 10);
for (int x = 0; x < flag.Height; ++x)
for (int y = 0; y < flag.Width; ++y)
flag.SetPixel(x, y, Color.White);
for (int x = 0; x < flag.Height; ++x)
flag.SetPixel(x, x, Color.Red);
return flag;
}
private void Form1_Load(object sender, EventArgs e)
{
pictureBox1.Image = CreateBitmap();
}
منبع : http://msdn2.microsoft.com/en-us/library/aa287582(VS.71).aspx
مثال: یک تکست باکس به فرم اضافه میکند:
private void button1_Click(object sender, System.EventArgs e)
{
TextBox myText = new TextBox();
myText.Location = new Point(25,25);
this.Controls.Add (myText);
}
توصیحات رو سر فرصت اضافه میکنم. فعلا :
http://www.codeproject.com/KB/databa...Result=success
ابتدا System.Management رو به References پروژه بیفزایید و سپس :
using System.Management;
private void GetMACAddress()
{
ManagementObjectSearcher searcher;
string qry = "select * FROM Win32_NetworkAdapter";
searcher = new ManagementObjectSearcher(qry);
foreach (ManagementObject wmi_HD in searcher.Get())
if (wmi_HD["MacAddress"] != null)
MessageBox.Show(wmi_HD["MacAddress"].ToString());
}