C#传递自定义结构体

利用WINDOWS消息循环的机制传递自定义的结构体在编程的过程中可能经常会用到,在这里我就编写了一个简单的结构体的传递代码,需要注意的是类是不能够传递的,能进行传递的只能是结构体

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace CustomTest
{
    public struct Student
    {
        public string name ;
        public string id;
    }

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private const int WM_USERMSG = 0x0400 + 1;

        [DllImport("User32.dll", EntryPoint = "SendMessage")]

        private static extern int SendMessage(

               IntPtr hWnd,   // handle to destination window

               int Msg,    // message

               int wParam, // first message parameter

               IntPtr lParam // second message parameter

         );


        protected override void DefWndProc(ref Message m)
        {
            switch (m.Msg)
            {
                case WM_USERMSG:
                    Student s = (Student)Marshal.PtrToStructure(m.LParam, typeof(Student));
                    MessageBox.Show(s.name, s.id);
                    break;

            }
            base.DefWndProc(ref m);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Student s = new Student();
            s.name = "zhouweigang";
            s.id = "11103132";
            IntPtr handle = IntPtr.Zero;
            handle = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Student)));
            Marshal.StructureToPtr(s, handle, true);

            if (handle != IntPtr.Zero)
            {
                SendMessage(this.Handle, WM_USERMSG, 0, handle);
            }
        }

    }
}

转载于:https://www.cnblogs.com/zhangpengshou/archive/2010/03/29/1699853.html

你可能感兴趣的:(C#传递自定义结构体)