SoFunction
Updated on 2025-03-04

Use of resource files in

Among them, the resource is a wide range and can be composed of multiple elements, including interface elements that interact with the user (such as bitmaps, icons, or cursors), custom files for data required by the application, and version files, menus, and dialog boxes used by the installation API can all be used as resources. By adding resources to the .Net assembly, you can implement resource reuse and other functions. It is easy to create resource files using the Visual Integrated Development Environment IDE. The method of adding resources to projects is as simple as adding forms and class libraries. You only need to set the "BuildAction" property of the resource to "Embedded Resource", so that you can use these resources
Create a resource
String tables are a very common resource. To create this type of resource file, there are two ways:
(1) Create using the .Net command line tool ResGen.First create a text file containing the resource content, which can be used (notepad, EditPlus and other text editors). This text file consists of the required "key-value pair". The name of the key can be referenced in the program. After setting the key name, the string value is assigned to the key to complete the creation of the file. As an example, the following statement segment generates such a resource and saves it as a file in the following format:

Copy the codeThe code is as follows:

Username="Songh";
Sex="Boy";
Birthday="1973-01-15";
Salary="5000RMB";

Then, convert the text file into a resource file, which is still achieved through the ResGen tool. Execute the following statement: ResGen, and the resource file will be generated. In addition, ResGen can also create .resX resource files based on XML format. Execute the following command ResGen will generate resources in Xml format. However, the ResGen tool does not support the operation of image resources, so the following method does not have such limitations.
(2) Use the ResourceWriter class.To facilitate creating resource files, the .Net structure provides a ResourceWriter class to support the creation of various resource types such as images. The ResourceWriter class contains methods that can write resources to an output file or output stream in the system's default format. Unlike Method 1), the unification here is completed in one process.
To create a resource file, call the constructor of the ResourceWriter class to initialize the class instance and provide at least the stream name or file name. The actual content of the resource is completed by calling the AddResource method, which specifies the resource as a name and value pair. The actual write to the resource requires the Generate method to be implemented, but the Generate method will be called implicitly when the Close method is called to close the ResourceWriter.
() method adds resources to the list to which resources are to be written. After creating a ResourceWriter class instance, this method can add up to 2GB of resources, one of the following overloaded methods is used to add string resources to the resource list:
Copy the codeThe code is as follows:

public void AddResource(
string name,//key name
string value//value
);

Here, the first parameter of the AddResource method specifies the key name and the second parameter specifies the value. The creation of the string table can be completed by calling this method multiple times. In addition, adding image resources can be achieved by instantiating the class Image (at this time, please add a namespace).
The following code snippet generates a resource file containing a string table and a picture.
Copy the codeThe code is as follows:

using System;
using ;
using ;
public class RS
{
public static void Main()
{
ResourceWriter rw=new
ResourceWriter("");// Provide the file name to initialize the ResourceWriter class instance.
Image image=(""); //Instantiate the Image class
("Photo",image);//Add image
("Username","songh");//Add string
("Sex","boy");//Add string
("Birthday","1973-01-15");//Add string
("Salary","5000RMB");//Add string
();//Close ResourceWriter and implicitly call the Generate() method to complete the resource file writing to the disk file.
}
}

The above code first opens the graphics file and creates an Image object. In doing so, this graphics file must exist in the directory of the project executable (usually the project's \Bin\Debug directory), or specify the full path of the image in the method parameters of(). Then, add the string resource to the ResourceWriter object by calling the AddResource() method several times. Finally, call the Close() method to close the ResourceWriter object and implicitly call the Generate() method to write the resource to the file.
Compile the above code and run it will create the resource file.
The resource files generated in the above two methods can be added to the assembly as an external file, or embedded in Dll or exe. The following continues to explain how to use resource files in Windows applications.
Using resource files
Using the Visual Integrated Development Environment IDE, it is easy to add resource files to the assembly. You only need to add an existing resource file to the created project, and simply set its properties to embed the resource file into the assembly. The following is a C# Windows console instance to illustrate any resource file created above.
First, create the C# Windows Console project ResourceUserinfo, open "Project\Add Existing Items", and find the resource file created earlier to add it to this project;
Then, select this resource file and set the property BuildAction to Embedded Resource so that the resource file can be embedded in the output assembly.
Now you can use this resource file. The ResourceManager class in the namespace provides easy access to specific resources at runtime. Specifically, it can be implemented through the GetObject and GetString methods, and the corresponding value will be returned with the key name as the parameter.
The constructor of the ResourceManager class initializes a new instance of the ResourceManager class, one of its overloaded methods looks for resources contained in some files that are exported from the specified root name using the given Assembly.
Copy the codeThe code is as follows:

public ResourceManager(
string baseName,
Assembly assembly
)

Where, the parameter baseName represents the root name of the resource. The root name consists of the application namespace and the resource file name (without extension). In this way, the root name of the resource in this example should be:, and the name can also be obtained programmatically by calling the GetManifestResourceNames() method.
Another parameter assembly represents the current main assembly. The main assembly in this example is actually the executing assembly. An easy way to get the executing assembly is to call the() method.
After obtaining the ResourceManager instance, you can obtain the corresponding resource by specifying the key name.
The following table is some of the controls used in the program:
Category TextBox TextBox TextBox TextBox PictureBox
Name username sex birthday salary photo
These controls can be dragged and dropped directly from the toolbox into the designer.
The complete source code is:
Method 1:
Copy the codeThe code is as follows:

using ;
using ;
private rm;
public Form1()
{
InitializeComponent();
Assembly assembly=();//Get the current main assembly
Rm=new ResourceManager("",assembly);//Instantiate resource management class
=(Image)("Photo");
=("Username");
=("Sex");
=("Birthday");
=("Salary");
}

Method 2:
Copy the codeThe code is as follows:

Assembly assm = ().Assembly;//(assembly path);
foreach (string resName in ())
{
Stream stream = (resName);
ResourceReader rr = new ResourceReader(stream);
IDictionaryEnumerator enumerator = ();
while (())
{
DictionaryEntry de = (DictionaryEntry);
//It's the resource name
//It's the resource content
}
}

Run the above code to retrieve the resource file content.
posted @ 2011-12-15 11:40 Tasting Reads (21) Comments (0) Edit
Use of DoDragDrop method
DoDragDrop method, used to start the drag and drop operation of an object.
The definition in the class library is:
Copy the codeThe code is as follows:

[UIPermissionAttribute(, Clipboard = )]
public DragDropEffects DoDragDrop(
Object data,
DragDropEffects allowedEffects
)

The data parameter is the data to be dragged and dropped. If the drag operation needs to be interoperated with the applications of another process, the data represented by data should be a basic managed class (String, BitMap, or MetaFile), or an object that implements ISerializable or IDataObject. The allowedEffects parameter represents the effect of drag and drop, and is an enumeration value (DragDropEffects). The return value is also the DragDropEffects enumeration value.
When you start calling the DoDragDrop method to drag a data object, during the drag and drop process, DoDragDrops detects whether the control at the current cursor position is effectively placed on the target. If the control under the current cursor is a valid placement target, the GiveFeedBack event is raised with the specified drag-and-drop effect. When detecting whether the cursor is a valid drag and drop target at the moment, the DoDragDrops method tracks changes in the cursor position, keyboard status, and mouse status at the same time.
(1) If used to move out a window, a DragLeave event is raised.
(2) If another control is moved into, the DragEnter event of the control is raised.
(3) If the mouse moves but stays in a control, a DragOver event is raised.
If a change in the keyboard or mouse state is detected, a QueryContinueDrag event of the drag-and-drop source is triggered, and the action is determined based on the Action property value of the event's QueryContinueDragEventArgs will continue to drag, place data or cancel the operation.
(1) If the Action property is specified as Continue, a DragOver event will be raised.
(2) If the Action property is specified as Drop, the placement effect is returned to the source so that the application can perform appropriate operations on the data; for example, if it is a moving operation, the data is cut.
(3) If the value of DragAction is Cancel, a DragLeave event will be raised
Excerpt from csdn a sample code:
The following code example demonstrates drag-and-drop operations between two ListBox controls. When the drag action starts, the example calls the DoDragDrop method. During the MouseDown event, if the distance from the mouse position is greater than SystemInformation..::.DragSize, the drag action is initiated. The IndexFromPoint method is used to determine the index of the item to be dragged during the MouseDown event.
The example also demonstrates how to use a custom cursor for drag and drop operations. This example requires that there are two cursor files in the application directory: and , for customizing dragging the cursor and prohibiting the parking cursor, respectively. If UseCustomCursorsCheckCheckBox is selected, a custom cursor is used. Custom cursors are set in the GiveFeedback event handler.
The keyboard status is calculated in the DragOver event handler on the right ListBox to determine which drag operation will occur based on the Shift, Ctrl, Alt, or Ctrl+Alt keys. The position where the placement action occurs in the ListBox is also determined during the DragOver event. If the data to be placed is not a String, then DragDropEffects will be set to None. Finally, the parking status is displayed in the DropLocationLabelLabel.
The data to be placed for the right ListBox is determined in the DragDrop event handler and the String value is added in the appropriate place in the ListBox. If the drag operation moves outside the form border, the drag and drop operation is cancelled in the QueryContinueDrag event handler
Copy the codeThe code is as follows:

using System;
using ;
using ;
namespace Snip_DragNDrop
{
public class Form1 :
{
private ListDragSource;
private ListDragTarget;
private UseCustomCursorsCheck;
private DropLocationLabel;
private int indexOfItemUnderMouseToDrag;
private int indexOfItemUnderMouseToDrop;
private Rectangle dragBoxFromMouseDown;
private Point screenOffset;
private Cursor MyNoDropCursor;
private Cursor MyNormalCursor;
/// The main entry point for the application.
[STAThread]
static void Main()
{
(new Form1());
}
public Form1()
{
= new ();
= new ();
= new ();
= new ();
();
// ListDragSource
(new object[] {"one", "two", "three", "four",
"five", "six", "seven", "eight",
"nine", "ten"});
= new (10, 17);
= new (120, 225);
+= new (this.ListDragSource_MouseDown);
+= new (this.ListDragSource_QueryContinueDrag);
+= new (this.ListDragSource_MouseUp);
+= new (this.ListDragSource_MouseMove);
+= new (this.ListDragSource_GiveFeedback);
// ListDragTarget
= true;
= new (154, 17);
= new (120, 225);
+= new (this.ListDragTarget_DragOver);
+= new (this.ListDragTarget_DragDrop);
+= new (this.ListDragTarget_DragEnter);
+= new (this.ListDragTarget_DragLeave);
// UseCustomCursorsCheck
= new (10, 243);
= new (137, 24);
= "Use Custom Cursors";
// DropLocationLabel
= new (154, 245);
= new (137, 24);
= "None";
// Form1
= new (292, 270);
(new [] {,
, ,
});
= "drag-and-drop Example";
(false);
}
private void ListDragSource_MouseDown(object sender, e)
{
// Get the index of the item the mouse is below.
indexOfItemUnderMouseToDrag = (, );
if (indexOfItemUnderMouseToDrag != ) {
// Remember the point where the mouse down occurred. The DragSize indicates
// the size that the mouse can move before a drag event should be started.
Size dragSize = ;
// Create a rectangle using the DragSize, with the mouse position being
// at the center of the rectangle.
dragBoxFromMouseDown = new Rectangle(new Point( - ( /2),
- ( /2)), dragSize);
} else
// Reset the rectangle if the mouse is not over an item in the ListBox.
dragBoxFromMouseDown = ;
}
private void ListDragSource_MouseUp(object sender, e) {
// Reset the drag rectangle when the mouse button is raised.
dragBoxFromMouseDown = ;
}
private void ListDragSource_MouseMove(object sender, e)
{
if (( & ) == ) {
// If the mouse moves outside the rectangle, start the drag.
if (dragBoxFromMouseDown != &&
!(, )) {
// Create custom cursors for the drag-and-drop operation.
try {
MyNormalCursor = new Cursor("");
MyNoDropCursor = new Cursor("");
} catch {
// An error occurred while attempting to load the cursors, so use
// standard cursors.
= false;
}finally {
// The screenOffset is used to account for any desktop bands
// that may be at the top or left side of the screen when
// determining when to cancel the drag drop operation.
screenOffset = ;
// Proceed with the drag-and-drop, passing in the list item.
DragDropEffects dropEffect = ([indexOfItemUnderMouseToDrag], | );
// If the drag operation was a move then remove the item.
if (dropEffect == ) {
(indexOfItemUnderMouseToDrag);
// Selects the previous item in the list as long as the list has an item.
if (indexOfItemUnderMouseToDrag > 0)
= indexOfItemUnderMouseToDrag -1;
else if ( > 0)
// Selects the first item.
=0;
}
// Dispose of the cursors since they are no longer needed.
if (MyNormalCursor != null)
();
if (MyNoDropCursor != null)
();
}
}
}
}
private void ListDragSource_GiveFeedback(object sender, e)
{
// Use custom cursors if the check box is checked.
if () {
// Sets the custom cursor based upon the effect.
= false;
if (( & ) == )
= MyNormalCursor;
else
= MyNoDropCursor;
}
}
private void ListDragTarget_DragOver(object sender, e)
{
// Determine whether string data exists in the drop data. If not, then
// the drop effect reflects that the drop cannot occur.
if (!(typeof())) {
= ;
= "None - no string data.";
return;
}
// Set the effect based upon the KeyState.
if (( & (8+32)) == (8+32) &&
( & ) == ) {
// KeyState 8 + 32 = CTL + ALT
// Link drag-and-drop effect.
= ;
} else if (( & 32) == 32 &&
( & ) == ) {
// ALT KeyState for link.
= ;
} else if (( & 4) == 4 &&
( & ) == ) {
// SHIFT KeyState for move.
= ;
} else if (( & 8) == 8 &&
( & ) == ) {
// CTL KeyState for copy.
= ;
} else if (( & ) == ) {
// By default, the drop action should be move, if allowed.
= ;
} else
= ;
// Get the index of the item the mouse is below.
// The mouse locations are relative to the screen, so they must be
// converted to client coordinates.
indexOfItemUnderMouseToDrop =
((new Point(, )));
// Updates the label text.
if (indexOfItemUnderMouseToDrop != ){
= "Drops before item #" + (indexOfItemUnderMouseToDrop + 1);
} else
= "Drops at the end.";
}
private void ListDragTarget_DragDrop(object sender, e)
{
// Ensure that the list item index is contained in the data.
if ((typeof())) {
Object item = (object)(typeof());
// Perform drag-and-drop, depending upon the effect.
if ( == ||
== ) {
// Insert the item.
if (indexOfItemUnderMouseToDrop != )
(indexOfItemUnderMouseToDrop, item);
else
(item);
}
}
// Reset the label text.
= "None";
}
private void ListDragSource_QueryContinueDrag(object sender, e) {
// Cancel the drag if the mouse moves off the form.
ListBox lb = sender as ListBox;
if (lb != null) {
Form f = ();
// Cancel the drag if the mouse moves off the form. The screenOffset
// takes into account any desktop bands that may be at the top or left
// side of the screen.
if ((( - ) < ) ||
(( - ) > ) ||
(( - ) < ) ||
(( - ) > )) {
= ;
}
}
}
private void ListDragTarget_DragEnter(object sender, e) {
// Reset the label text.
= "None";
}
private void ListDragTarget_DragLeave(object sender, e) {
// Reset the label text.
= "None";
}
}
}

For the relationship between this drag-and-drop operation and Microsoft's services and container mode, you can learn later.
posted @ 2011-12-15 11:16 Tasting Reads (92) Comments (0) Edit
About the use of interfaces
Overview: The use of interfaces reflects a generalized idea.
One of the application scenarios is:
(1) Several classes must implement certain actions, and the specific implementation method of this action is different.
For example, for a form that creates a condition, it is necessary to add a form that adds a condition of the shaping parameters, bool type parameters and string type parameters. In the specific implementation of shaping and string forms, and the addition of bool type, the implementation details are different.
Copy the codeThe code is as follows:

public interface IExpressionForm
{
ConditionItemEntity CIEntity { get; set; }
ConditionBranchEntity CIEntity { get; set; }
event Handle OnExpressionHandled; }

For each form, it is necessary to include CIEntity, CIEntity attributes and OnExpressionHandled events after adding conditions. Therefore, CIEntity, CIEntity, and OnExpressionHandled are defined in the IExpressionForm interface.
Then implement the conditional condition of plastic shaping parameters to add the form
Copy the codeThe code is as follows:

public partial class frmNumericCondition : Form, IExpressionForm
{
public frmNumericCondition()
{
InitializeComponent();
}
public ConditionItemEntity CIEntity { get; set; }
public ConditionBranchEntity CBEntity { get; set; }
public event Handle OnExpressionHandled;
}

Then add the form with the character parameter condition
Copy the codeThe code is as follows:

public partial class frmVarcharCondition : Form, IExpressionForm
{
public frmVarcharCondition()
{
InitializeComponent();
}
public ConditionItemEntity CIEntity { get; set; }
public ConditionBranchEntity CBEntity { get; set; }
public event Handle OnExpressionHandled;
}

And so on, implement forms added with other parameter type conditions.
So what are the benefits of my purpose of achieving this? Next, let's take a look at a function that generates a form that I defined
Copy the codeThe code is as follows:

public static IExpressionForm CreateExpressionForm(ConditionType ct)
{
IExpressionForm frm = null;
if (ct == )
frm = new frmBitCondition();
else if (ct == )
frm = new frmDateTimeCondition();
else if (ct == )
frm = new frmNumericCondition();
else if (ct == )
frm = new frmVarcharCondition();
return frm;
}

From the definition, we can see that the return value type is IExpressionForm, which is the interface I defined above. Therefore, this function can return all classes that implement the IExpressionForm interface. Such as frmVarcharCondition and frmNumericCondition.
This simply implements the factory model and the program can be used with good scalability.
The above is just one of the application scenarios of the interface, and it was also discovered when I was writing the code. Not well written. But you also need to write. On the one hand, you need to summarize your work and study. You can think and discover when summarizing, and hope to help those who read the article.