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

Monday, February 28, 2011

how to export a function from c# dll

Introduction

In this article, I would like to explain how to create and use DLLs in C Sharp. Before writing code, we will examine some basics of a DLL in the .NET framework; for example, how it's loaded in the process address space, how CLR is initialized, and the mechanism behind the screen. First, we will talk about MSCorEE.dll; you will find this guy in the %windir%\system32\ directory. MSCorEE.dll stands for Microsoft Component object runtime Execution Engine. The existence of this file tells you that you have installed the .NET framework in your system. This DLL is responsible for initializing the CLR.
Whenever you create an assembly, the compiler/linker emits the following 6-byte x86 stub function into the PE file's .text section:
JMP _CorExeMain for Exe or JMP _CorDllMain for Dll.
Figure 1 shows the Portable Executable (PE) file format. This stub function is implemented inside the MSCorEE.dll. So, this dll must be referenced somewhere in the PE file. Yes, your guess is right; it's referenced in the .idata section of the PE file. The .idata section is used to refer import libraries for assembly.

Figure 1—The PE file format.
We have given all the hints and clues to the Windows loader, so here we go.... When the managed assembly file is invoked, the Windows loader completes the following steps:
  1. Loads the PE file, parses the .idata section, and loads MSCorEE.dll (if it's not already loaded) into the process's address space.
  2. Takes the address of _CorExeMain in the case of an Exe assembly, or _CorDllMain in the case of a DLL assembly function, inside the MSCoreEE.dll.
  3. Using the address from Step 2, the Windows loader fixes the stub function JMP instruction (from the .text section PE).
At this point, the process's primary thread starts executing the stub function; that is, it jumps to _CorExeMain for Exe or _CorDllMain for Dll in the MSCorEE.dll. The _CorExeMain or _CorDllMain initializes the CLR and looks for a managed entry point from the assembly's CLR header and starts executting. Here the IL code for the method is compiled into native CPU instructions and the CLR jumps to native code. That's it; the managed applications code is running.
The framework differentiates between managed executive and managed DLL files because of the stub function stored in the .text section of the PE file. For Exe, the stub function is JMP _CorExeMain and for Dll the stub function is JMP _CorDllMain. The Windows loader differentiates this function and fixes the corresponding address from the MSCorEE.dll.
I think now we know how a managed exe/dll loads in the process address space and how CLR gets initialized. Okay, time for coding. Here we develop a small DLL and a test container for that. This DLL will export three functions, each from one class in a namespace.
Open a new C# WindowsApplication project in Visual Studio .NET. Name the Project MathFunctions.
Add the following three classes to this project. Name them something like AddClass.cs, MultiClass.cs, and FactorialClass.cs.
Listing 1. AddClass.cs
using System;

namespace MathFunctions
{
  public class AddClass
  {
    public static int Add(int a, ant b)
    {
      return (a+b);
    }
  }
}
Listing 2. MultiClass.cs
using System;

namespace MathFunctions
{
  public class MultiClass
  {
    public static int Multiply(int a, int b)
    {
      return (a*b);
    }
  }
}
Listing 3. FactorialClass.cs
namespace MathFunctions
{
  public class FactorialClass
  {
    public static int Factorial(int i)
    {
      return((i <= 1) ? 1 : (i * Factorial(i-1)));
    }

  }
}
Our idea is to export AddClass::Add, MultiClass:: Multiply, and FactorialClass::Factorial from the namespace MathFunctions. That's it; we're finished coding.
Go to the command line and type the following.
CSC /target:library /out:MyFunctions.dll AddClass.cs
     MultiClass.cs FactorialClass.cs
Go to the command line option /target:library and ask the C Sharp Compiler/Linker to output a DLL instead of an EXE. It's possible to have a different name for the DLL; for example, /out:MyFunctions.dll directs the compiler to output the DLL with the name MyFunctionsLib; otherwise, it will take the default name from the first .cs file. Here, it's AddClass.dll.
Now comes the test container for this DLL. Create a new WindowsApplication project by right-clicking the solution in the Solution Explorer pane. Name it DllTestApp.
Add the following line to the Using section.
using MathFunctions;
Add the following code to the click of button1.
private void button1_Click(object sender, System.EventArgs e)
{
int add = AddClass.Add(125,125);
  int mul = MultiClass.Multiply(25,25);
  int fac = FactorialClass.Factorial(5);

  string str = "Addition result = " + add.ToString() + "\n"
       + "Multiplication result = " + mul.ToString() + "\n"
       + "Factorial result = " + fac.ToString();

  MessageBox.Show(str, "MyDllTestDialog");

}
To refer to the DLL in our project, right-click the project's reference and click Add Reference. This displays tabbed panes that list the various types of components and projects you can browse. On the .NET tab, click the Brows button and browse for the DLL to which you want to refer (here, MyFunctions.dll), and click OK.

Sunday, February 13, 2011

how to load one form in to another form c#


Introduction
In this article, I will explain basics of Multiple Document Interface (MDI) applications. MDI applications let you to show multiple documents at the same time, with every document displayed in its individual window.
Creating MDI Parent FormsThe base of a Multiple Document Interface (MDI) is the MDI parent form. This is the form that holds the MDI child windows, which are all the "sub-windows" in which the client work together with the MDI application.
To Create MDI Parent Forms:
Create a new form and add the code.

this.IsMDIContainer = true;

This assign the form as an MDI container for child windows.
Creating MDI Child FormsAn vital constituent of Multiple Document Interface (MDI) Applications is the MDI child forms, as these are the main windows for client interaction.
To Create MDI Child Forms:
Form frmchild=new Form();
frmchild.MDIParent=
this;
frmchild.Show();
Determining the Active MDI Child:
In a number of circumstance, we desire to give a command that operates on the control with the focus on the at present active child form.

For the reason that an application can have many instances of the same child form, the process wants to be acquainted with which form to use. To specify this, use the ActiveForm property of an MDI Form, which returns the child form that has the focus.

In any case one MDI child form must be loaded and visible when you access the ActiveForm property, or an error is returned.
Arranging Child Forms:
Frequently, applications will have menu commands for actions such as Tile, Cascade, and Arrange, with concerning to the open MDI child forms. One can use the LayoutMDI method with the MDILayout enumeration to rearrange the child forms in an MDI parent form.
The MDILayout enumeration can be set to four different values, which will display child forms as cascading, as horizontally or vertically. Often, these methods are used as the event handlers called by a menu item's Click event. In this way, a menu item with the text "Cascade Windows" can have the desired effect on the MDI child windows.
In the example below, the event handler for the Click event for the Cascade menu item sets the MDILayout enumeration to Cascade for the child windows of the MDI Parent form.
Example:

 using System; 
using System.ComponentModel;                                                                                    using System.WinForms;                                                                                               using System.Drawing;
 public class MDI :Form
{

 private MainMenu mainMenu;private int Count=0; 
public MDI()
{
 

this.IsMDIContainer=true;this.Text="MDI Demo";
mainMenu =
new MainMenu();
MenuItem File = mainMenu.MenuItems.Add("&File");
File.MenuItems.Add(
new MenuItem("&New",new EventHandler this.FileNew_clicked),Shortcut.CtrlN));
File.MenuItems.Add(
new MenuItem("&Active Child",new EventHandler this.FindActive_clicked),Shortcut.CtrlA));
File.MenuItems.Add(
new MenuItem("-"));
File.MenuItems.Add(
new MenuItem("&Exit",new EventHandler this.FileExit_clicked),Shortcut.CtrlX));
MenuItem Arrange = mainMenu.MenuItems.Add("&Arrange");
Arrange.MenuItems.Add(
new MenuItem("&Cascade",new EventHandler this.Cascade_clicked),Shortcut.F1));
Arrange.MenuItems.Add(
new MenuItem("&Horizontal",new EventHandler this.Horizontal_clicked),Shortcut.F2));
Arrange.MenuItems.Add(
new MenuItem("&Vertical",new EventHandler this.Vertical_clicked),Shortcut.F3));this.Menu=mainMenu;
mainMenu.GetForm().BackColor = Color.Indigo ;
}
 

private void FileExit_clicked(object sender, EventArgs e)
{
 

this.Close();
}
 

private void FindActive_clicked(object sender, EventArgs e)
{
MessageBox.Show(
this.ActiveMDIChild.Text,"MDI FORM",MessageBox.IconInformation);
}

 private void FileNew_clicked(object sender, EventArgs e)
{
Form frmchild=
new Form();
frmchild.MDIParent=
this;
frmchild.Show();
frmchild.Text="Child Form" + Count.ToString();
Count++;
}
 

private void pop_Clicked(object sender, EventArgs e)
{
MessageBox.Show("Popupmenu","MENU_CREATION",MessageBox.IconInformation);
}

 private void Cascade_clicked(object sender, EventArgs e){this.LayoutMDI(MDILayout.Cascade );
}
 

private void Horizontal_clicked(object sender, EventArgs e)
{

 this.LayoutMDI(MDILayout.TileHorizontal);
}
 

private void Vertical_clicked(object sender, EventArgs e)
{
 

this.LayoutMDI(MDILayout.TileVertical);
}
 

public static void Main(string[] args)
{
Application.Run(
new MDI());
}
}

Thursday, February 10, 2011

How to Show color in font dialog c#

Type: System.Boolean
true if the dialog box displays the color choice; otherwise, false. The default value is false.
The following code example uses ShowDialog to display a FontDialog. This code requires that a Form has already been created with a TextBox and button placed on it. It also requires that the fontDialog1 has been created. The Font contains the size information but not the color information.

C#

private void button1_Click(object sender, System.EventArgs e)
 {
    fontDialog1.ShowColor = true;

    fontDialog1.Font = textBox1.Font;
    fontDialog1.Color = textBox1.ForeColor;

    if(fontDialog1.ShowDialog() != DialogResult.Cancel )
    {
       textBox1.Font = fontDialog1.Font ;
       textBox1.ForeColor = fontDialog1.Color;
    }
 }
 

Tuesday, February 8, 2011

How To Learn Visual C++ 2005

Learn Visual C++ 2005

Visual Studio Team Edition for Software Developers with MSDN Premium Subscription

What Is Visual C++ 2005?

Microsoft Visual C++ 2005 provides a powerful and flexible development environment for creating Microsoft Windows–based and Microsoft .NET–based applications. It can be used as an integrated development system, or as a set of individual tools. Visual C++ is comprised of these components:
Visual C++ 2005 compiler tools - The compiler has new features supporting developers that target virtual machine platforms like the Common Language Runtime (CLR). There are now compilers to target x64 and Itanium. The compiler continues to support targeting x86 machines directly, and optimizes performance for both platforms.

Visual C++ 2005 Libraries - This includes the industry-standard Active Template Library (ATL), the Microsoft Foundation Class (MFC) libraries, and standard libraries such as the Standard C++ Library, and the C RunTime Library (CRT), which has been extended to provide security enhanced alternatives to functions known to pose security issues. A new library, the C++ Support Library, is designed to simplify programs that target the CLR.

Visual C++ 2005 Development Environment - Although the C++ compiler tools and libraries can be used from the command-line, the development environment provides powerful support for project management and configuration (including better support for large projects), source code editing, source code browsing, and debugging tools. This environment also supports IntelliSense, which makes informed, context-sensitive suggestions as code is being authored.
In addition to conventional graphical user-interface applications, Visual C++ enables developers to build Web applications, smart-client Windows-based applications, and solutions for thin-client and smart-client mobile devices. C++ is the world's most popular systems-level language, and Visual C++ gives developers a world-class tool with which to build software.

What Are the Differences Between the Visual C++ Editions?

The Visual C++ 2005 Express Edition is a lightweight, easy to use and easy to learn tool for hobbyist, novice, and student developers who want to build dynamic Windows applications. The Visual C++ 2005 product team has put together a series of Hands-on Tutorial Videos for people who are new to the Express Edition.
For the professional developer who needs the ultimate in power in order to design and produce timely and robust Windows and Web applications, Visual C++ is included with the award-winning Visual Studio interactive development editor (IDE). There are currently three different editions of Visual Studio (all of which include Visual C++). Click here to see a grid comparison of all the Visual C++/Visual Studio editions.

Where Can I Find Sample Applications?

MSDN provides two distinct types of sample applications in order to help developers who are new to Visual C++ 2005 become more productive faster than ever. The first type of sample is a set of walk-through samples, where the developer is taken step-by-step through the process of performing a programmatic task such as extending the famous "Scribble" MFC application to support a plug-in model using .NET to demonstrating the use of reflection in a pure MSIL (Microsoft Intermediate Language) application.
In addition, MSDN also features a Visual C++ 2005 Samples page dedicated to samples that cover every aspect of programming with Visual C++ 2005. This includes such tasks as programming with Standard Template Library (STL), ATL, internationalization, .NET interoperability, Platform SDK and much more.
Finally, if you can't find the exact example you're looking for, we recommend browsing through the list of third-party community sites where you'll find thousands of source-code examples and tutorials.

How Do I Learn More About Visual C++ 2005?

MSDN provides many starting points for learning about Visual C++ 2005 depending on your need. If you're looking for product information such as a feature overview or system requirements, you can visit the Product Information page. On other hand, if you're looking to learn more about the product from a usage (developer) standpoint, here are some great resources that will help get you underway very quickly:
  • What's New in Visual C++ 2005 - Discover all the changes to the libraries, IDE and compiler as well as information on such topics as how to port, or upgrade, your existing projects.
  • Getting Started - This page contains links to such information as supported platforms, Visual C++ settings and how to create and manage your Visual Studio 2005 projects.
  • Guided Tour - For the newcomer to Visual C++, this page could become your best friend as it covers many common tasks such as how to: compile a code example found on MSDN, create a command-line applications, convert between different types, use the IDE more efficiently, create and use dynamic and static libraries and more. There's even a page for Unix developers new to Visual C++.
  • How do I ... ? - As software developers we're always wanting to learn more. Therefore, we've created a page for such inquisitive people where the most commonly asked about topics are categorized for your convenience. For example, if you have a question regarding the performance of a mixed-mode application (containing both native and managed code), you would go to the How-To page and click on Interop where where one of the topics is entitled Performance Considerations for Interop (C++).