Showing posts with label C Sharp. Show all posts
Showing posts with label C Sharp. Show all posts

Thursday, October 13, 2011

Printing a Text File (Visual C#)


System.IO.StreamReader fileToPrint;
System.Drawing.Font printFont;
private void printButton_Click(object sender, EventArgs e)
{
   string printPath = System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
   fileToPrint = new System.IO.StreamReader(printPath + @"\myFile.txt");
   printFont = new System.Drawing.Font("Arial", 10);
   printDocument1.Print();
   fileToPrint.Close();
}

private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
   float yPos = 0f;
   int count = 0;
   float leftMargin = e.MarginBounds.Left;
   float topMargin = e.MarginBounds.Top;
   string line = null;
   float linesPerPage = e.MarginBounds.Height/printFont.GetHeight(e.Graphics);
   while (count < linesPerPage)
   {
      line = fileToPrint.ReadLine();
      if (line == null)
      {
         break;
      }
      yPos = topMargin + count * printFont.GetHeight(e.Graphics);
      e.Graphics.DrawString(line, printFont, Brushes.Black, leftMargin, yPos, new StringFormat());
      count++;
   }
   if (line != null)
   {
      e.HasMorePages = true;
   }
}

Printing the Form (Visual C#)


//use gdi to print the form.
[System.Runtime.InteropServices.DllImport("gdi32.dll")]
public static extern long BitBlt (IntPtr hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hdcSrc, int nXSrc, int nYSrc, int dwRop);
private Bitmap memoryImage;
private void CaptureScreen()
{
   Graphics mygraphics = this.CreateGraphics();
   Size s = this.Size;
   memoryImage = new Bitmap(s.Width, s.Height, mygraphics);
   Graphics memoryGraphics = Graphics.FromImage(memoryImage);
   IntPtr dc1 = mygraphics.GetHdc();
   IntPtr dc2 = memoryGraphics.GetHdc();
   BitBlt(dc2, 0, 0, this.ClientRectangle.Width, this.ClientRectangle.Height, dc1, 0, 0, 13369376);
   mygraphics.ReleaseHdc(dc1);
   memoryGraphics.ReleaseHdc(dc2);
}
//get the current form and print it in memory
private void printDocument1_PrintPage(System.Object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
   e.Graphics.DrawImage(memoryImage, 0, 0);
}
//button to click for capturing screen and printing the form
private void printButton_Click(System.Object sender, System.EventArgs e)
{
   CaptureScreen();
   printDocument1.Print();
}

Tuesday, June 28, 2011

Namespaces (C# Programming)

Namespaces have the following properties:
  • They organize large code projects.
  • They are delimited by using the . operator.
  • The using directive obviates the requirement to specify the name of the namespace for every class.
  • The global namespace is the "root" namespace: global::System will always refer to the .NET Framework namespace System.

    namespace SampleNamespace
    {
        class SampleClass
        {
            public void SampleMethod()
            {
                System.Console.WriteLine(
                  "SampleMethod inside SampleNamespace");
            }
        }
    }
     
     
     

Using Structs (C# Programming)

public struct CoOrds
{
    public int x, y;

    public CoOrds(int p1, int p2)
    {
        x = p1;
        y = p2;
    }
}

Classes (C# Programming)

public class Person
{
    // Field
    public string name;

    // Constructor
    public Person()
    {
        name = "unknown";
    }

    // Method
    public void SetName(string newName)
    {
        name = newName;
    }
}
class TestPerson
{
    static void Main()
    {
        Person person = new Person();
        Console.WriteLine(person.name);

        person.SetName("John Smith");
        Console.WriteLine(person.name);

        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}

C# Preprocessor Directives

This section discusses the C# language's preprocessor directives:
#if
#else
#elif
#endif
#define
#undef
#warning
#error
#line
#region
#endregion
#pragma
#pragma warning
#pragma checksum
While the compiler does not have a separate preprocessor, the directives described in this section are processed as if there was one; these directives are used to aid in conditional compilation. Unlike C and C++ directives, you cannot use these directives to create macros.
A preprocessor directive must be the only instruction on a line.

Thursday, June 16, 2011

Creating Icon from a image file in C#


using System; 
using System.Drawing; 
using System.IO; 
string sourceFile, destinationFile; sourceFile = "C:\imagen.jpg"; 
destinationFile = Path.ChangeExtension(sourceFile, ".ico"); 
using (Bitmap bitmap = Image.FromFile(sourceFile, true) as Bitmap) 
{ 
using (Icon icon = Icon.FromHandle(bitmap.GetHicon())) 
{
using (Stream imageFileStream = File.Create(destinationFile)) 
  { 
icon.Save(imageFileStream); 
Console.WriteLine("File Created - {0}", destinationFile); 

} 
}
}

C# how to Run the application at Windows startup


private void RegisterInStartup(bool Checked)
{
    RegistryKey registryValue= Registry.CurrentUser.OpenSubKey
            ("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
    if (Checked))
    {
        registryKey.SetValue("startupApplication", Application.ExecutablePath);
    }
    else
    {
        registryKey.DeleteValue("startupApplication");
    }
}

Download File from URL, Download Document from SharePoint library using c#


public void DownloadFileFromSite(string siteURL, string saveName  )
{
    try
    {
        System.Net.WebClient _WebClient = new System.Net.WebClient();
        // Downloads the resource with the specified URI to a local file.
        _WebClient.DownloadFile(siteURL, saveName);
}
    catch (Exception _Exception)
    {
        // Error
       MessageBox.Show("Error In Downloading");
    }
}

Tuesday, May 17, 2011

C# Method Wizard


Add a method and define its elements using the one-page C# Method Wizard.
Method access
Sets the access to the method. Access modifiers are keywords for setting access to the method. Specify the access other classes have to the method. The method access level is set to public by default. The following access levels are available: See Accessibility Levels for an overview of these five levels and for more information about specifying access for methods.
Return type
Sets the value type that the method returns in the return statement. The return type is set to void by default. For more information about C# return types, see Value Typesand Built-in Types Table.The following value types are available:
Method name
Sets the name of the method to add to the class. You must add at least the method name.
Modifier
Sets the parameter's modifier. Modifier is set to None by default. See Method Parameters for more information.
Parameter type
Sets the type for the Parameter name. The parameter type is set to int by default. The type is reflected in the Method signature box at the bottom of the wizard. The same values available for the return type are available for the parameter type, with the exception of void.
Parameter name
Sets the name of a parameter to pass through your method. After typing the name, you must click Add to add it to the list of parameters that will pass through your method.If you do not provide a parameter name, the wizard ignores any Modifier or Parameter type selections. Once you click Add, the parameter name appears in Parameter list and in Method signature at the bottom of the wizard. If you supply a parameter name and then click Finish before you click Add, the parameter is not added to the method. You must find the method and insert the parameter manually.
Add
Adds the parameter you specify in Parameter name, and its modifier and type, to the Parameter list and displays the complete parameter in the Method signature box at the bottom of the wizard. You must click Add to add a parameter to the list.
Remove
Removes the parameter you select in Parameter list from the list and from the Method signature box at the bottom of the wizard.
Parameter list
Displays all parameters and their modifiers and types currently added for the method. As you add parameters, the wizard updates the Parameter list to display each parameter, with its modifier and type.
Method modifiers
Modifies the declarations of types and type members. By default, no modifiers are included. Using this wizard, you can add the following modifiers.
Modifier optionDescription
StaticThe method belongs to the type itself rather than to a specific object.
AbstractThe method is a member of an abstract class. If the class to which you are adding the method is not abstract, this option is not available. See C# Class Wizard for more information.
VirtualThe method's implementation can be changed by an overriding member in a derived class.
ExternAdvanced. The method is implemented externally.
OverrideAdvanced. Provide a new implementation of a virtual member inherited from a base class.
NewAdvanced. Explicitly hides a member inherited from a base class. To hide an inherited member, declare it in the derived class using the same name, and modify it with the new modifier.
You can combine certain modifiers; however, some modifiers are mutually exclusive. For example, you can set your modifiers to new virtual, extern static or override abstract. The following combinations of options are not allowed:
ModifierCannot combine with ...
staticvirtual, abstract, and override
virtualstatic, abstract, and override
overridenew, static, and virtual
abstractvirtual and static
newoverride
externabstract
Depending on your modifier selection, check boxes appear dimmed for excluded combinations.
Comment
Provides a short description to the method. Comments are converted into XML documentation and encapsulated by <summary> tags, which are used to provide the descriptions.
Method signature
Displays the method as it is added to your code when you click Finish. You cannot edit the text in this box. To change the method, change the appropriate fields in the wizard.

Featured Posts

Kali Linux Remote Desktop: Access GNOME from Windows Using Native RDP

  Kali Linux + GNOME 50 + GNOME Remote Desktop + Windows Remote Desktop (MSTSC) Getting a full GNOME desktop remotely on Kali Linux can be ...