http://www.pinvoke.net
معرفی و آموزش api ها
Printable View
http://www.pinvoke.net
معرفی و آموزش api ها
انتقال محتویات DatagridView به یک Datatable:
DataTable dt = new DataTable();
private void getDgvToDt()
{
//کپی دیتا گرید در دیتا تیبل وقتی دیتا سرس وجود داشته باشد
//var dt2 = ((DataTable)dataGridView1.DataSource).Copy();
//
//کپی دیتا گرید در دیتا تیبل وقتی دیتا سرس وجود داشته نباشد
//table.Columns.AddRange(dataGridView1.Columns.Cast< DataGridViewColumn>().Select(c => new DataColumn(c.Name)).ToArray());
dt.Columns.Add("StartDate");
dt.Columns.Add("EndDate");
dt.Columns.Add("Name");
DataRow row;
foreach (DataGridViewRow dgvr in dataGridView1.Rows)
//dt.Rows.Add(row.Cells.Cast<DataGridViewCell>().Sel ect(cell => cell.Value).ToArray());
{
row = dt.NewRow();
row["StartDate"] = dgvr.Cells["ClmnStartDate"].Value.ToString();
row["EndDate"] = dgvr.Cells["ClmnEndDate"].Value.ToString();
row["Name"] = dgvr.Cells["ClmnName"].Value.ToString();
dt.Rows.Add(row);
}
}
در مورد متد ها ونحوه فراخوانی.
private void BiggerWindow()
{
this.Height += 200;
this.Width += 200;
}
private void button1_Click(object sender, EventArgs e)
{
BiggerWindow();
}
private void ChangeSizeForm(int x, int y)
{
this.Width = x;
this.Height = y;
}
private void ChangeSizeForm(string x, string y)
{
this.Width = Convert.ToInt16(x);
this.Height = Convert.ToInt16(y);
}
private void button2_Click(object sender, EventArgs e)
{
ChangeSizeForm(textBox1.Text, textBox2.Text);
}
private int sum(int x, int y)
{
return (x + y);
}
private int sum(int x, int y, int z)
{
return (x + y + z);
}
private void button3_Click(object sender, EventArgs e)
{
int a;
a = sum(12, 45, 2);
MessageBox.Show(a.ToString());
}
int a = 10, b = 5;
private void ShowIt()
{
label1.Text = a.ToString();
label2.Text = b.ToString();
}
private void Double1(int x, int y)
{
x *= 2; y *= 2;
}
private void Double2(ref int x, ref int y)
{
x *= 2; y *= 2;
}
private void button4_Click(object sender, EventArgs e)
{
Double1(a, b);
}
private void button5_Click(object sender, EventArgs e)
{
Double2(ref a, ref b);
}
private void button6_Click(object sender, EventArgs e)
{
ShowIt();
}
تبدیل عکس به آرایه ای از بایت ها و بالعکس
public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms,System.Drawing.Imaging.ImageFormat .Gif);
return ms.ToArray();
}
public Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
کد به حرکت در آوردن متن که دونه به دونه به متن اضافه میشه و وقتی کامل شد دوباره از اول شروع میشه.
برای اینکه یک متن رو به حرکت در بیاورید اول باید یک Timer و Label یا Textbox روی برنامه قرار داده . و مقدار interval رو برای به حرکت در آوردن متن تعیین کنید. من 360 رو پیشنهاد میکنیم سرعت خوبی هستش ولی هر مقداری خواستید خودتان می توانید تعیین کنید و مقدار Enable= true قرار بدید.
private static int si = 0;
و در داخل رویداد این دستور رو وارد فرمایید.
private void TimSayeBan_Tick(object sender, EventArgs e)
{
try
{
string str = "نرم افزار حسابداری سایه بان";
if (LblSayeBan.Text.ToString().Length < str.Length)
{
LblSayeBan.Text = str.Substring(0, si) + "";
si += 1;
}
else
{
LblSayeBan.Text = "";
si = 0;
}
}
catch
{
}
}
و وقتی که این کد رو اضافه کردید اون موقع برنامه رو اجرا کنید و مبینید که متن داخل Label شروع به حرکت کردن میکند.
کد به حرکت در آوردن فرم به وسیله فرم و ابزار های که روی فرم قرار دارد.
1- اول باید using انجام داد.using System.Runtime.InteropServices;
2- باید توابع API رو وارد کرد.//کد مربوط به جابه جایی برنامه
public const int WM_NCLBUTTONDOWN = 0xA1;
public const int HT_CAPTION = 0x2;
[DllImportAttribute("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
[DllImportAttribute("user32.dll")]
public static extern bool ReleaseCapture();
3- بعد در رویداد ابزار مورد نظر که میخواهید فرم رو حرکت بدید یعنی در رویداد Mouse Down آن ابزار چی فرم یا ابزار دیگر هستش این کد را بنویسید.private void frmLoad_MouseDown(object sender, MouseEventArgs e)حالا وقتی شما روی ابزار خود موس را نگر میدارید و موس را تکان میدهید فرم شما تکان میخورد. بدون هیچ مشکل و خطای
{
if (e.Button == MouseButtons.Left)
{
ReleaseCapture();
SendMessage(this.Handle, 0xa1, 0x2, 0);
}
}
کد جلوه دادن به دکمه که وقتی روی دکمه میریم بیاد جلو وقتی موس از روش ور داریم برگرد به حالت اول.
برای اینکه به دکمه جلوه بدیم باید .
1- وارد کلاس program بشیم و این دستورات رو وارد کنیم. به این صورت
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace AppSoftwareHesabDarePoshak
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(fals e);
Application.Run(new frmLoad());
}
#region Just Style the Buttons
public static void MakebuttonStyle(Button button)
{
button.MouseEnter += new EventHandler(button_MouseEnter);
button.MouseLeave += new EventHandler(button_MouseLeave);
}
private static void button_MouseLeave(object sender, EventArgs e)
{
Button button = (Button)sender;
button.FlatStyle = FlatStyle.Standard;
button.Font = new System.Drawing.Font(button.Font.FontFamily, button.Font.Size);
button.ForeColor = System.Drawing.SystemColors.ControlText;
}
private static void button_MouseEnter(object sender, EventArgs e)
{
Button button = (Button)sender;
button.FlatStyle = FlatStyle.Flat;
button.Font = new System.Drawing.Font(button.Font.FontFamily, button.Font.Size, System.Drawing.FontStyle.Bold);
button.ForeColor = System.Drawing.SystemColors.ButtonHighlight;
}
#endregion
}
}
2- حالا برای اینکه ببینیم دکمه ما وقتی موس روش میره میاد بالا یا نه وارد یکی از فرم ها میشم و در بالا فرم قسمت Initialize Component(); دستور رو به این صورت میدهیم.
public FrmAddCompany()
{
InitializeComponent();
Program.MakebuttonStyle(this.BtnAdd);
Program.MakebuttonStyle(this.BtnExit);
Program.MakebuttonStyle(this.BtnMin);
Program.MakebuttonStyle(this.BtnOpenPic);
}
و وقتی برنامه رو اجرا میکنیم میبینیم که وقتی موس روی دکمه میرود میاد جلو وقتی از روی دکمه میرود بر میگرد به حالت اول.
هر دکمه که میخواهیم جلوه بدهیم در قسمت Initialize Component میدهیم.
کد در صورت نبودن زبان فارسی روی سیستم باعث پیغام به شخص شود که زبان فارسی در سیستم نصب نمی باشد.
برای اینکه به شخص پیغام دهیم که زبان فارسی روی سیستم شما نصب نیست در قسمت Initialize Component این دستور رو وارد میکنیم.
public FrmAddCompany()
{
InitializeComponent();
try
{
InputLanguage.CurrentInputLanguage = InputLanguage.FromCulture(System.Globalization.Cul tureInfo.CreateSpecificCulture("fa-IR"));
}
catch
{
PersianMessageBox.Show("برای استفاده از برنامه باید زبان فارسی را نصب کنید");
}
}
و زبان فارسی روی سیستم نصب بیشه دیگه این پیغام ظاهر نمی شود. و از این کد
InputLanguage.CurrentInputLanguage = InputLanguage.FromCulture(System.Globalization.Cul tureInfo.CreateSpecificCulture("fa-IR"));
رو اگه فقط در change text box داده شود طرف وقتی میخواهد تایپ کنید فقط می تواند فارسی تایپ کنی فقط و به زبان دیگر نمی تواند تایپ کنید ولی وقتی در قسمت Initialize Component تعریف کنید برنامه اول به صورت فارسی میاد و وقتی دکمه alt+shift رو بزنه می تواند به غیر از فارسی انگلیسی هم تایپ کند.
کد تغییر اندازه تصویر در تکس باک موقع وارد کردن تصویر در Picture box
برای اینکه اندازه تصویر را عوض کنید اول باید. این دستور ها رو خارج از رویداد تعریف کنید.
//کد برای تغییر اندازی تصویر
#region public Memebers
public Image picimage = Properties.Resources.whitebackgound;
#endregion
#region Propersties
private int _imgwidth
{
get { return 120; }
}
private int _imgHieght
{
get { return 140; }
}
#endregion
#region public Function
public Bitmap ResizeBitMap(Bitmap b, int nWidth, int nHeight)
{
Bitmap result = new Bitmap(nWidth, nHeight);
using (Graphics g = Graphics.FromImage((Image) result)) g.DrawImage(b, 0, 0, nWidth, nHeight);
return result;
}
#endregion
و وقتی که خارج از برنامه تعریف کردید در دکمه یا قسمتی که قسط باز کردن تصویر و دادن آن به Picturebox را دارید به این صورت دستور رو وارد فرمایید.
private void imageshow()
{
try
{
OpenFileDialog openFile = new OpenFileDialog();
openFile.Filter = "(*.JPG) تصاویر|*.jpg|" + "(*.GIF) تصاویر|*.Gif" + "(*.PNG) تصاویر|*.PNG" + "" + "(*.*) تمام تصاویر|*.*";
openFile.Title = "انتخاب تصویر";
openFile.ShowDialog();
float imgWidth = System.Drawing.Image.FromFile(openFile.FileName).P hysicalDimension.Width;
float imgHieght = System.Drawing.Image.FromFile(openFile.FileName).P hysicalDimension.Height;
picimage = System.Drawing.Image.FromFile(openFile.FileName);
if (imgWidth > _imgwidth || imgHieght > _imgHieght)
{
string strMessage = "تصویر انتخابی شما نباید بزرگتر از {1}*{0} پی کسل باشد" + "\n" +
"آیا تمایل به تغییر اندازه عکس دارید ؟";
if (
PersianMessageBox.Show(string.Format(strMessage, _imgwidth, _imgHieght), "پیام سیستم",
PersianMessageBox.Buttons.YesNo, PersianMessageBox.Icon.Warning) == DialogResult.Yes)
{
picimage = ResizeBitMap((Bitmap) picimage, _imgwidth, _imgHieght);
PicShowImage.Image = picimage;
}
else
{
picimage = Properties.Resources.whitebackgound;
PicShowImage.Image = picimage;
}
}
else
{
PicShowImage.Image = picimage;
}
}
catch
{
}
}
private void btnOpen_Click(object sender, EventArgs e)
{
imageshow();
}
اعلان شما میگوید چرا من در خارج دکمه دستور باز کردن تصویر و کوچک کردن تصویر رو انجام میدم و در دکمه فقط صدا میکنیم . دلیل این کار من این می باشد که من از contextMenuStrip1 هم استفاده میکنیم در پروژه اگه دستور باز کردن رو در جفت کپی پست کنیم در صورت داشتن اشغال باید هر جفت دستور رو بگردم که دادم که خطا از کجا بودی یا هی کپی پست کنیم ولی وقتی در خارج از رویداد میسازم دستور رو و در رویداد کلیک دکمه یا contextMenuStrip1 مورد نظر صدا میکنیم وقتی اشغالی پیش بیاد فقط دستور که در خارج از دکمه و contextMenuStrip1 قرار دادم و درست میکنیم و وقتی دکمه یا کلیک روی یکی از منو contextMenuStrip1 میشود دستور از همون خطی که صدا کردم صدا میشه تا با مشکل برخورد نکنیم. و همچنین دیگه هی کپی پست روی هم نمی خواهد.
فقط یک نکته می ماند. من در این دستور برای تغییر ساز از این دستور برای ساخت تصویر استفاده کردم.picimage و این دستور مربوط به ابزار تصویر می باشد.PicShowImage
کد در صورت خالی بودن تکس باکس و کادر تصویر پیغام دهید. به وسیله error Provider و همچنین Message box
برای اینکه کادر تصویر خالی رها نشود رنگ کادر متن عوض شود.
1- باید اول textbox رو انتخاب کرد. و در قسمت Properties از رویداد ها ، رویداد leave رفته و این دستور رو وارد فرمایید.
if (TxtAddNumber.Text.Trim() == "")
TxtAddNumber.BackColor = Color.Red;
else
{
TxtAddNumber.BackColor = Color.White;
}
2- حالا میخواهیم روی دکمه ذخیره کلیک کنیم و وقتی تکس باکس هنوز خالی بود اطلاعات ذخیره نشه و روی همون تکس باکس برود. برای این کار باید از return استفاده شود. این دستور
if (TxtAddNumber.Text.Trim() == "")
{
errorProvider1.SetError(TxtAddNumber, "لطفاً شماره ثبت را وارد فرمایید");
TxtAddNumber.Focus();
return;
}
3- حالا میخواهیم وقتی تکس باکس پور شود همون لحظه رنگ ضمینی تکس باکس سفید بیشه و علامت errorProvider1 برود این دستور رو وارد میکنیم. در قسمت text change
private void TxtAddNumber_TextChanged(object sender, EventArgs e)
{
errorProvider1.SetError(TxtAddNumber,string.Empty) ;
if (TxtAddNumber.Text.Trim() != "")
{
TxtAddNumber.BackColor = Color.White;
}
}
4- و حال میخواهیم وقتی عکس در داخل تکس باکس نبود پیغام خطا ظاهر شود از این دستور استفاده میکنیم.
if (PicShowImage.Image == null)
{
PersianMessageBox.Show("شما تصویری برای لوگو شرکت انتخاب نکردید؟", "تصویری رو انتخاب فرمایید",
PersianMessageBox.Buttons.OK, PersianMessageBox.Icon.Error);
btnOpen.Focus();
return;
}
یک نکته ما وقتی میخواهیم عکسی رو در داخل دیتابیس ذخیره می کنیم و هیچ عکس و برای ذخیره نمیدهم و موقع اجرا برنامه دیتاگرید ویو که میخواهد اطلاعات رو نمایش دهد خطا میدهد یا روی دیتاگرید کلیک میکنید خطا میدهد این به این علت هستش که مقدار فیلد جدول دیتابیس رو var binary قرار دادید و مقداری در این فیلد باید قرار بگرید ولی شما مقداری قرار ندادید خطا میدهد.
افزودن برنامه به استارت آپ ویندوز
using Microsoft.Win32;
public static void AddToStartUpKey(string AppName, string AppPath)
{
RegistryKey key = Registry.LocalMachine.OpenSubKey(@"Software\Micros oft\Windows\CurrentVersion\Run",
true);
key.SetValue(AppName, AppPath);
}
public static void RemoveFromStartUpKey(string AppName)
{
RegistryKey key = Registry.LocalMachine.OpenSubKey(@"Software\Micros oft\Windows\CurrentVersion\Run",
true);
key.DeleteValue(AppName, false);
}
قرار دادن پروکسی برای ویندوز
using Microsoft.Win32;
public static void SetProxy(string Host, string Port)
{
RegistryKey registry = Registry.CurrentUser.OpenSubKey("Software\\Microso ft\\Windows\\CurrentVersion\\Internet Settings", true);
registry.SetValue("ProxyEnable", 1);
registry.SetValue("ProxyServer", Host + ":"+ Port);
}
public static void DeleteProxy(string Host, string Port)
{
RegistryKey registry = Registry.CurrentUser.OpenSubKey("Software\\Microso ft\\Windows\\CurrentVersion\\Internet Settings", true);
registry.SetValue("ProxyEnable", 0);
registry.DeleteValue("ProxyServer");
}
افزودن URL به Favorites
public static void AddToFavorites(string Title, string URL)
{
StreamWriter wr =
File.CreateText(Environment.GetFolderPath(Environm ent.SpecialFolder.Favorites).ToString() + "\\" +
Title + ".url");
wr.WriteLine("[DEFAULT]");
wr.WriteLine("BASEURL=" + URL);
wr.WriteLine("[InternetShortcut]");
wr.WriteLine("URL=" + URL);
wr.Close();
}
بررسی اینکه کاربر فعلی ادمین هست یا نه
using System.Security.Principal;
public static bool IsAdmin()
{
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
string role = "BUILTIN\\Administrators";
bool IsAdmin = principal.IsInRole(role);
return IsAdmin;
}
کد جالبی توو codeproject بود :
using System;using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace Utility
{
/// <summary>
/// Base form class that provides fading/sliding effects on open/close of the form.
/// </summary>
public abstract class FadeForm : Form
{
#region Win32
const int AW_HIDE = 0X10000;
const int AW_ACTIVATE = 0X20000;
const int AW_HOR_POSITIVE = 0X1;
const int AW_HOR_NEGATIVE = 0X2;
const int AW_SLIDE = 0X40000;
const int AW_BLEND = 0X80000;
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern int AnimateWindow
(IntPtr hwand, int dwTime, int dwFlags);
#endregion
#region Variables
private bool _UseSlideAnimation;
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="FadeForm"/> class.
/// </summary>
public FadeForm() : this(false) { }
/// <summary>
/// Initializes a new instance of the <see cref="FadeForm"/> class.
/// </summary>
/// <param name="useSlideAnimation">if set to <c>true</c> [use slide animation].</param>
public FadeForm(bool useSlideAnimation)
{
_UseSlideAnimation = useSlideAnimation;
}
#endregion
#region Overrides
/// <summary>
/// Raises the <see cref="E:System.Windows.Forms.Form.Load"/> event.
/// </summary>
/// <param name="e">An <see cref="T:System.EventArgs"/> that contains the event data.</param>
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
AnimateWindow(this.Handle, 1000, AW_ACTIVATE | (_UseSlideAnimation ? AW_HOR_POSITIVE | AW_SLIDE : AW_BLEND));
}
/// <summary>
/// Raises the <see cref="E:System.Windows.Forms.Form.Closing"/> event.
/// </summary>
/// <param name="e">A <see cref="T:System.ComponentModel.CancelEventArgs"/> that contains the event data.</param>
protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
base.OnClosing(e);
if (e.Cancel == false)
{
AnimateWindow(this.Handle, 1000, AW_HIDE | (_UseSlideAnimation ? AW_HOR_NEGATIVE | AW_SLIDE : AW_BLEND));
}
}
#endregion
}
}
اگر برروی مکانی که breakpoint گذاشته شده راست کلیک کنید یک گزینه می بیند بنام condition شما می توانید با این امکان برای debug کردن شرط بگذارید . فقط دقت داشته باشید که سرعت برنامه پایین می آید
سلام
رنگهای دیگری را خودتان اضافه نمایید
using System;
namespace s02
{
class Program
{
static void Main(string[] args)
{
for (int i = 1; i <=10; i++)
{
for (int j = 1; j<= 10; j++)
{
int result = j * i;
if (result % 2==0)
{
Console.ForegroundColor = ConsoleColor.DarkGreen;
Console.Beep();
}
if (result % 3 == 0)
{
Console.ForegroundColor = ConsoleColor.Yellow;
}
Console.Write(result + "\t");
Console.ResetColor();
}
Console.WriteLine();
}
Console.ReadKey();
}
}
}
using System;
namespace s02
{
class Program
{
static void Main(string[] args)
{
var MultiplyArray = new int[10, 10];
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
MultiplyArray[i, j] = (i + 1)*(j + 1);
}
}
for (int i = 0; i <10; i++)
{
for (int j = 0; j < 10; j++)
{
if (i %2==0)
{
Console.ForegroundColor = ConsoleColor.Yellow;
}
Console.Write( "{0}\t",MultiplyArray[i,j] );
Console.ResetColor();
}
Console.WriteLine();
}
}
}
}
using System;
using System.Threading;
namespace S031
{
enum WeekDay
{
Sundy=1,
Mondy=3,
}
class Iran
{
static void Main()
{
foreach (var VARIABLE in "Linq in Csharp")
{
Console.ForegroundColor = GetColor();
Console.Write(VARIABLE);
}
Console.ResetColor();
Console.ReadKey();
}
static ConsoleColor GetColor()
{
var r = new Random(DateTime.Now.Millisecond);
Thread.Sleep(100);
switch (r.Next(7))
{
case 0:
return ConsoleColor.DarkGray;
case 1:
return ConsoleColor.Blue;
case 2:
return ConsoleColor.Cyan;
case 3:
return ConsoleColor.Magenta;
case 4:
return ConsoleColor.White;
default:
return ConsoleColor.Red;
}
}
}
using System;
using System.Threading;
namespace Sc022
{
class Program
{
public static void Main()
{
var str= createRandomWord(5);
Console.WriteLine(str);
}
public static string createRandomWord(int lenght)
{
var temp = string.Empty;
var random = new Random(DateTime.Now.Millisecond);
for (int i = 0; i < lenght; i++)
{
temp += (char)(random.Next((int)'a', (int)'z'));
}
return temp;
}
}
}
ایجاد یک پنجره کنسول (Console Window) و اجرا دستورات به صورت مخفی در آن
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
startInfo.FileName = "YourApp.exe";
startInfo.CreateNoWindow = true;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
منبع: stackoverflow.com
تابع محاسبه ب.م.م به روش بازگشتی :
static int gcd(int x, int y)
{
int Ret = 0;
if (y <= x && x % y == 0)
Ret = y;
else if (x < y)
Ret = gcd(y, x);
else
Ret = gcd(y, x % y);
return Ret;
}
تابع معکوس یک رشته :
public static string ReverseString(string s)
{
char[] arr = s.ToCharArray();
Array.Reverse(arr);
return new string(arr);
}
یک برنامه جمع و جور کنسولی برای جایگشت . توجه کنید که برای ورودی از شما یک استرینگ درخواست میشود مثل ABC .
در خروجی جایگشتهای آن ، یعنی ABC، ACB، BAC و ... درج میشود . میدانیم که تعداد جایگشتهای n شی متمایز برابر n فاکتوریل است .
//-------------------------------------------------//
//---- نوشته شده توسط محمد جواد پيشوايي ----- //
//---- Microsoft Visual Studio 2010 ----- //
//---- ConsoleApplication ----- //
//------- جایگشتهای n عنصر --------------------//
//-------------------------------------------------//
using System;
using System.Linq;
using System.Collections;
using System.Text;
using System.IO;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
namespace ConsoleApplication
{
class Program
{
static int n;
static char[] mArr;
static void Main(string[] args)
{
string str;
Console.Write("we obtain permutation of n character In a string . please input string (Ex:ABC) =>");
str = Console.ReadLine();
mArr=str.ToCharArray();
n=mArr.Length-1 ;
perm(0 );
Console.ReadKey();
}
//-----------------------------------------------------------------------------------------------------------------------
static void perm(int k)
{
if (k == n)
Console.WriteLine ( String.Concat(mArr));
else
{
for (int i = k; i <= n; i++)
{
char temp = mArr[i];
mArr [i] = mArr[k];
mArr[k] = temp;
perm(k + 1);
mArr[k] = mArr[i];
mArr[i] = temp;
}
}
}
//-----------------------------------------------------------------------------------------------------------------------
}
}
این قابل تغییر هست:
در سازنده فرم CheckForIllegalCrossThreadCallsرو false کنید میتونید از کنترلهای threadهای دیگه هم (از جمله برنامه اصلی) استفاده کنیدنقل قول:
نکته :
هر Threadفقط میتواند با object هایی کار کند که خودش آنها را ایجاد کرده است. مثلا اگر در متد DoSomethingشما بخواهید با یک label که روی فرم است کار کنید cross-thread exception رخ خواهد داد چون آن label بوسیله Threadاصلی برنامه ایجاد شده است.
public Form1() {
InitializeComponent();
CheckForIllegalCrossThreadCalls = false;
}
با تشکر
با پوزش؛
نمی دانم چرا اکثر ما برنامه نویسا عادت کردیم لقمه را بچرخونیم. خوب ساده ترش این باید باشد:
SqlConnection c1 = newSqlConnection("Data Source=studio;InitialCatalog=AccountDb;Integrated Security=True");
SqlCommand cmd1 = newSqlCommand("InsertGroup", c1); cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.AddWithValue("@Code", txtb_Code_G.Text);
cmd1.Parameters.AddWithValue("@Sal", txtb_Sal_Mali.Text);
cmd1.Parameters.AddWithValue("@Name", txtb_Name_G.Text); c1.Open(); cmd1.ExecuteNonQuery(); c1.Close();
روش اول:
باعث غیرفعال شدن راست کلیک و کلید های ترکیبی
CTRL+Z,CTRL+E,CTRL+C,CTRL+Y,CTRL+X,CTRL+BACKSPACE, CTRL+V,CTRL+DELETE,CTRL+A,SHIFT+DELETE,CTRL+L,SHIF T+INSERT,CTRL+R
در TextBox میشه
private void Form1_Load(object sender, EventArgs e)
{
textBox1.ShortcutsEnabled = false;
}
روش دوم:
private void Form1_Load(object sender, EventArgs e)
{
textBox1.ContextMenuStrip = new ContextMenuStrip();
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode==Keys.V) //غیر فعال کردن عملکرد paste
{
e.SuppressKeyPress = true;
}
}
ذخیره کردن هر نوع فایلی در متغیر byte
byte[] fd;
OpenFileDialog o = new OpenFileDialog();
if (o.ShowDialog() != DialogResult.Cancel)
{
filename = o.FileName;
FileStream st = new FileStream(filename, FileMode.Open, FileAccess.Read);
FileInfo fi = new FileInfo(filename);
fd = new byte[fi.Length];
st.Read(fd, 0, (int)fi.Length);
st.Close();
}
تنظیم تکس باس برای دریافت ورودی واحد پول "تومان"
private void txt1_TextChanged_1(object sender, EventArgs e)
{
if (txt1.Text == string.Empty)
{
return;
}
else
{
txt1.Text = string.Format("{0:0,00}", double.Parse(txt1.Text));
txt1.Select(txt1.Text.Length, 0);
}
}
public class CpuUsing {
private readonly PerformanceCounter _cpuUsing = new PerformanceCounter();
public double Progress()
{
_cpuUsing.CategoryName = "Processor";
_cpuUsing.CounterName = "% Processor Time";
return _cpuUsing.NextValue();
}
}
طریقه استفاده
باید قطعه کد زیر در رویداد کنترل تایمر نوشته شود و پروپرتی تایمر ترو شود
label1.Text = "میزان مصرف پردازنده : " + new CpuUsing().Progress() + " % ";
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;
}
با استفاده از این کلاس.هرچنتا تکس باکس با هر نامی روی فرم باشه رو خالی میکنه
نحوه صدا زدنش به این صوررتهutility.MyTextBoxes(this, "Clear");
یه کلاس ایجاد کنین و کد های زیر درونش قرار بدین
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
public class utility
{
public static void MyTextBoxes(Control container, string CommandName)
{
foreach (Control c in container.Controls)
{
MyTextBoxes(c, CommandName);
if (c is TextBox)
{
switch (CommandName)
{
case "Clear":
c.Text = "";
break;
case "ReadOnly":
((TextBox)c).ReadOnly = true;
break;
}
}
}
}
}
با سلام کسی dll های نرم افزار حضور و غیاب رو داره یا میتونه راهنمایی کنه از کجا میتونم تهیه کنم
شنیدین میگن سی شارپ یه دریای بیکرانه از امکاناته؟ واقعاً هم همینطوره! هر چقدر بیشتر باهاش کار میکنم، بیشتر متوجه عمق و قدرتش میشم. یه نکته کوچیک ولی خیلی کاربردی که تو این مدت یاد گرفتم اینه که چقدر استفاده درست از LINQ (Language Integrated Query) میتونه کد رو خواناتر و کوتاهتر کنه. قبلاً برای فیلتر کردن یا مرتب کردن لیستها کلی حلقه foreach مینوشتم، ولی الان با LINQ میتونم همون کار رو با یه خط کد شبیه به کوئریهای SQL انجام بدم. این نه تنها سرعت توسعه رو بالا میبره، بلکه نگهداری کد رو هم خیلی آسونتر میکنه. اگه تازه شروع کردین به یادگیری این زبان شیرین، حتماً یه نگاه جدی به LINQ بندازین، چون واقعاً یه ابزار قدرتمند تو جعبه ابزار هر برنامه نویس سی شارپ به حساب میاد. برای یادگیری عمیقتر این مبحث و کلاً آموزش برنامه نویسی سی شارپ، توصیه میکنم دنبال منابعی بگردین که LINQ رو به صورت جامع توضیح دادن و مثالهای عملی زیادی دارن.