如何使用P / Invoke SendMessage设置边距?

时间:2009-12-08 10:20:53

标签: c# .net sendmessage

此主题取决于How to add button to textbox?

感谢。

2 个答案:

答案 0 :(得分:4)

这是一个支持RightMargin属性的文本框控件。在Win7上测试:

using System;
using System.ComponentModel;
using System.Windows.Forms;
using System.Runtime.InteropServices;

class MyTextBox : TextBox {
  private int mRightMargin;

  [DefaultValue(0)]
  public int RightMargin {
    get { return mRightMargin; }
    set {
      if (value < 0) throw new ArgumentOutOfRangeException();
      mRightMargin = value;
      if (this.IsHandleCreated) updateMargin();
    }
  }

  protected override void OnHandleCreated(EventArgs e) {
    base.OnHandleCreated(e);
    if (mRightMargin > 0) updateMargin();
  }

  private void updateMargin() {
    // Send EM_SETMARGINS
    SendMessage(this.Handle, 0xd3, (IntPtr)2, (IntPtr)(mRightMargin << 16));
  }

  [DllImport("user32.dll", CharSet = CharSet.Auto)]
  private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);
}

答案 1 :(得分:2)

根据the documentation

[DllImport("user32.dll", CharSet=CharSet.Auto)]
static extern IntPtr SendMessage(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam);

...

SendMessage(hwnd, EM_SETMARGINS, (IntPtr)EC_RIGHTMARGIN, (IntPtr)(rightMargin << 16));