Skip to content

First Script Postfix

StompyNZ edited this page Apr 3, 2019 · 9 revisions

Our first example is a Postfix patch for the terminal window of a dedicated server.

WinFormConnectionPatch.cs

using Harmony;
using System.Drawing;
using System.Windows.Forms;

namespace HarmonyPatches
{
  [HarmonyPatch(typeof(WinFormConnection))]
  [HarmonyPatch("initialize")]
  class WinFormConnectionPatch
  {
    static void Postfix(RichTextBox ___consoleOutputBox)
    {
      ___consoleOutputBox.BackColor = Color.WhiteSmoke;
      ___consoleOutputBox.ForeColor = Color.SteelBlue;
      ___consoleOutputBox.Font = new Font(FontFamily.GenericMonospace, 12f, FontStyle.Bold);
    }
  }
}

A Postfix patch will run the code after the original method has executed.

In this instance, we are patching WinFormConnection.initialize

'initialize' is a private method on the WinFormConnection class, which is the terminal window for a dedicated server.

private void initialize()
{
        <snip>

	BackColor = Color.Black;
	ForeColor = Color.DarkGreen;
	consoleOutputBox = new RichTextBox
	{
		Dock = DockStyle.Fill,
		Multiline = true,
		ScrollBars = RichTextBoxScrollBars.Both,
		Font = new Font(FontFamily.GenericMonospace, 10f),
		ReadOnly = true,
		BackColor = BackColor,
		ForeColor = ForeColor,
		BorderStyle = BorderStyle.None
	};
	base.Controls.Add(consoleOutputBox);

        <snip>
}

The above code is part of the original method. In this example, the BackColor, ForeColor, and Font are what we are aiming to change on the private consoleOutputBox field.

In a Postfix to access a private variable we include it in the method definition as the exact name with three underscores prefixed to the name "___consoleOutputBox".

In our patch, the new colors are assigned and the font is increased slightly in size.

You can also access the instance if the method being patched is not static with the __instance param (two underscores), and the return value from the original method can be included with the param __result (also two underscores).

More info on patch variables in the official Harmony wiki.

Because the patch is using System.Drawing and System.Windows.Forms those dlls need to be in the scripts folder so that SDX can use them to compile. If you are using a visual studio project you can add these dlls as references to the project and then you will be able to make use of IntelliSense for code completion and validation.

Clone this wiki locally