Sunday, 7 November 2010

Thủ thuật Winform C# - P1

Sau đây là một số thủ thuật xử lí với winform trên C#

>>>Làm thế nào thiết lập một default button ?
1. Set tabindex = 0;
2. Set lập thuộc tính trên form cho button

Code:
form1.AcceptButton = button1;
>>>Làm thế nào để in 1 form qua máy in nhỉ?
1. Cho vào chương trình component : PrintDocument
2. Dùng hàm mẫu sau :

Code:
private void printFormToPrinter()
{
  PrintDialog printDialog1 = new PrintDialog();
  printDialog1.Document = printDocument1;
  DialogResult result = printDialog1.ShowDialog();
  if ( result == DialogResult.OK )
    printDocument1.Print();
}
3. Vẽ form khi ra máy in 

Code:
using System.Drawing.Printing;

private void printDocument1_PrintPage( object sender, PrintPageEventArgs e)
{
  Graphics graphic = CreateGraphics();
  Image memImage = new Bitmap( Size.Width, Size.Height, graphic );
  Graphics memGraphic = Graphics.FromImage( memImage );
  IntPtr dc1 = graphic.GetHdc();
  IntPtr dc2 = memGraphic.GetHdc();
  BitBlt( dc2, 0, 0, ClientRectangle.Width,
    ClientRectangle.Height, dc1, 0, 0, 13369376 );
  graphic.ReleaseHdc( dc1 );
  memGraphic.ReleaseHdc( dc2 );
  e.Graphics.DrawImage( memImage, 0, 0 );
}
>>>Làm thế nào lấy bitmap của một form ?

Code:
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.Windows.Forms;

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

  private const Int32 SRCCOPY = 0xCC0020;

  public void SaveImage( string filename )
  {
    using ( Graphics g1 = CreateGraphics() )
    {
      Image image =
        new Bitmap( ClientRectangle.Width, ClientRectangle.Height, g1 );
      using ( Graphics g2 = Graphics.FromImage( image ) )
      {
        IntPtr dc1 = g1.GetHdc();
        IntPtr dc2 = g2.GetHdc();
        BitBlt( dc2, 0, 0, ClientRectangle.Width, ClientRectangle.Height,
          dc1, 0, 0, SRCCOPY );
        g2.ReleaseHdc( dc2 );
        g1.ReleaseHdc( dc1 );
      }
      image.Save( filename, ImageFormat.Bmp );
    }
  }
}
>>>Làm thế nào lấy giá trị của Txtbox trong form này trong khi nó nằm ở form khác ?

Code:
string strValue = myFormA.TextBox1.Text;
>>>Không cần làm form active mà vẫn show được  ?
Muốn show mà không cần active form :

Code:
TrickClass.SetVisibleNoActivate( myForm, true );
Muốn hide đi :

Code:
TrickClass.SetVisibleNoActivate( myForm, false );
Định nghĩa tạm cho TrickClass với cách xài method :

Code:
public class TrickClass 
{
  [ DllImport( "user32.dll" ) ]
  extern public static bool SetWindowPos( IntPtr hWnd,
    IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, int uFlags );
 
  public const int HWND_TOPMOST = -1; // 0xffff
  public const int SWP_NOSIZE = 1; // 0x0001
  public const int SWP_NOMOVE = 2; // 0x0002
  public const int SWP_NOACTIVATE = 16; // 0x0010
  public const int SWP_SHOWWINDOW = 64; // 0x0040
  
  public static void ShowWindowTopMost( IntPtr handle )
  {
    SetWindowPos( handle, (IntPtr) HWND_TOPMOST, 0, 0, 0, 0,
      SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE | SWP_SHOWWINDOW );
  }
 
  public static void SetVisibleNoActivate( Control control, bool visible )
  {
    if ( visible )
      ShowWindowTopMost( control.Handle );
    control.Visible = visible;
  }
}
>>>Làm thế nào để bắt hết được các kiểu exception xảy ra trên form nhỉ ?

Code:
using System.Threading;

[STAThread]
public static void Main()
{
  Application.ThreadException +=
    new ThreadExceptionEventHandler( UnhandledExceptionCatcher );
  Application.Run( new Form1() );
}

private static void UnhandledExceptionCatcher(object sender,
  ThreadExceptionEventArgs e)
{
  Console.WriteLine( "bắt được Exception nè :D !" );
}
>>>Làm thế nào để thiết lập icon của form từ bitmap nhỉ?

Code:
Form form1 = new Form();
Bitmap bmp = imageList1.Images[index] as Bitmap;
form1.Icon = Icon.FromHandle(bmp.GetHicon());
>>>Làm thế nào để chỉnh sửa thông tin về công ty làm chương trình nhỉ  ?

Code:
// Vào file : AssemblyInfo.cs
[assembly: AssemblyCompany( "Pete đại ca Corporation :D" )]
>>>Làm thế nào để hiện ra một hộp thoại status trong một thread nền trong khi đang thực hiện việc khác và cho phép người dùng stop nó nhỉ ?

Code:
private void button1_Click(object sender, System.EventArgs e)
{
BackgroundThreadStatusDialog statusDialog = new BackgroundThreadStatusDialog();
try
{
for (int n = 0; n < 1000; n++)
{
statusDialog.Percent = n/10;
int ticks = System.Environment.TickCount;
while (System.Environment.TickCount - ticks < 10)
;
if (statusDialog.IsCanceled)
return;
}
statusDialog.Close();
MessageBox.Show(statusDialog.IsCanceled ? "Canceled" : "Success");
}
finally
{
statusDialog.Close();
}
}
>>>Làm thế nào biết được người dùng click vào một một form khác từ một model dialog ?

Code:
/* Dùng Form.Deactivate */
Deactivate += new EventHandle( OnDeactivate );
// ...

private void OnDeactivate( object s, EventArgs e )
{
  Close();
}
>>>Làm thế nào load một control từ một assembly hay DLL ?

Code:
using System.Reflection // caí này để load control
// ví dụ lấy SpecControls.ColorControl từ SpecControls.dll.
using System.Reflection;

Assembly assembly = Assembly.LoadFrom( "SpecControls.dll" );
Type t = assembly.GetType( "SpecControls.ColorControl" );

// tạo instance rồi add nó vào parent control
Control c = (Control) Activator.CreateInstance( t );
parent.Controls.Add( c );
>>>Làm thế nào cấm user thoát khỏi chương trình bằng nút X nhỉ ?

Code:
private void Form1_Closing( object sender, CancelEventArgs e )
{
  if ( NotOkToClose() )
    e.Cancel = true; //don't close
}
>>>Làm thế nào tạo form không có title bar và resize được ?

Code:
form1.Text = string.Empty;
form1.ControlBox = false;
>>>Làm thế nào thiết lập độ trong suốt cho form nhẩy ?
Dùng thuộc tính Opacity

Code:
form1.Opacity = X // với X là kiểu double   0 <= X <= 1 , hoặc 0% <= X <= 100% :D
>>>Tạo form hình chữ nhật chán quá, tạo hình khác được không?
Ví dụ cho form có kiểu 1 hình chữ nhật *****g một elipse

Code:
GraphicsPath gp = new GraphicsPath();
gp.AddEllipse( 0, 0, 100, 100 );
gp.AddRectangle( 50, 50, 100, 100);
this.Region = new Region( gp );
>>>Làm thế nào form có style kiểu WinXP nhỉ?

Code:
public virtual void Main()
{
  Application.EnableVisualStyles();
  // Calling DoEvents after the above method call seems to fix this issue
  Application.DoEvents();
  Application.Run( new Form1() );
}
>>> Làm thế nào tạo form phủ hết màn hình kể cả taskbar ?

Code:
FormBorderStyle = FormBorderStyle.FixedSingle;
Rectangle formrect = Screen.GetBounds( this );
Location = formrect.Location;
Size = formrect.Size;
<còn tiếp>

No comments:

Post a Comment